From dcde39284459c7efa177c683f50c538d4ffe0fea Mon Sep 17 00:00:00 2001 From: Kevin Williams Date: Wed, 25 Nov 2026 00:09:14 +0000 Subject: [PATCH 1/6] fix(ui): make a change of signed-in user the only inventory session boundary MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The inventory masked itself behind "Checking inventory access…", re-ran host loaders and re-read all collections whenever the tab was hidden or the host revalidated (for example on a theme change), and cancelled in-flight saves. No other staff-portal page does this, and per-request authorization already covers what it protected. Match the host instead: - Tab hide/show, pagehide/pageshow and focus leave inventory, cache, forms and in-flight saves alone. - Navigation keeps the current view on screen until the host has loaded. - A host revalidation for the same user pauses new reads and operations while it runs; nothing on screen changes. - A change of signed-in user (including A→B→A) or of non-presentation URL parameters replaces the private cache, with one fresh read. Tests for the removed hidden/pagehide/revalidation behaviour are removed; new tests cover inventory, forms and saves surviving tab switches. The design doc records the decision and the retained protections. Co-Authored-By: Claude Opus 5.5 --- docs/development/staff-inventory-ui.md | 99 ++++++----- .../components/adversarial-review.test.tsx | 14 -- .../components/device-placement-edit.test.tsx | 4 +- .../src/components/device-placement-edit.tsx | 11 +- .../exact-head-independent.test.tsx | 54 +----- .../inventory-management-lifetime.test.tsx | 44 ++++- .../src/components/inventory-management.tsx | 12 +- .../inventory-navigation-safety.test.tsx | 14 +- .../inventory-session-boundary.test.tsx | 132 +++------------ .../components/inventory-session-boundary.tsx | 158 +++++++----------- .../inventory-stable-controls.test.tsx | 2 +- .../inventory-tab-navigation.test.tsx | 47 ++---- .../inventory-visible-focus-save.test.tsx | 2 +- .../pr103-review-negatives.test.tsx | 54 ------ .../reviewer-exact-staging.test.tsx | 74 -------- .../src/pages/inventory-create.test.tsx | 2 +- 16 files changed, 231 insertions(+), 492 deletions(-) diff --git a/docs/development/staff-inventory-ui.md b/docs/development/staff-inventory-ui.md index 3c2e50f1..e20f5d2f 100644 --- a/docs/development/staff-inventory-ui.md +++ b/docs/development/staff-inventory-ui.md @@ -272,15 +272,17 @@ access-dependent navigation descriptions in the historical phase notes below. access results. No private record names or counts appear in the public shell. - Pending, allowed, and denied directory states share the heading and the toolbar's search, filter, action and status slots. Actions remain mounted - and disabled until usable; successful authorization adds no “access checked” - clutter. Missing management access and ownership restrictions are the + and disabled until usable; neither a pending permission check nor a + successful one adds visible text. Missing management access and ownership restrictions are the disabled button's tooltip and accessible description, not a sentence. Explanations for unavailable references, expired sessions, and uncertain saves remain visible. Long failure explanations may wrap rather than being clipped. The composition follow-up below replaces expanding forms with focused dialogs and child task pages. - Existing immutable edit baselines, submit-time authorization, read/write - generation guards, principal/logout and hidden/pagehide fences are retained. + generation guards and principal/logout fences are retained. Hidden/pagehide + fences were removed on 2026-11-24 (see + [Session boundary](#session-boundary-a-change-of-signed-in-user-implemented)). Visible window blur/focus remains a complete no-op, including draft, DOM, request, loader, and operation-authority behavior. @@ -523,48 +525,61 @@ original UID/resourceVersion and use atomic JSON Patch test operations. They do not silently adopt a refreshed baseline. No automatic write retries occur. Existing session protections are retained: principal-isolated QueryClients, -authority invalidation at session/revalidation/navigation/background/unmount -boundaries, fresh authority generations even for React-batched revalidation, -and generation-guarded background-return checks. Already-dispatched uncertain +operation invalidation at principal/revalidation/navigation/unmount boundaries, +and a fresh cache even for a React-batched A→B→A principal change. Already-dispatched uncertain outcomes stay unknown rather than becoming cancelled-success. -### Browser focus is not a session boundary - -Implemented against PR103's merged staging base -`f190d28397fc6110e02c9c83e6819a3a584258d0`. Ordinary visible window blur/focus -is deliberately ignored. Opening the URL bar does not change the session: -it does not suspend reads or writes, reset edit baselines, close or disable forms, -change controls, or start host/permission/inventory requests. -Both the session boundary and individual management/location forms have no -blur/focus listeners. QueryClient defaults and inventory queries disable window -focus refetch. Drafts and frozen baselines remain usable without reopening. - -Actual document hidden/pagehide events still synchronously invalidate operation -and read scopes, cancel queries and mask private children. Visibility restoration -or pageshow revalidates the host only after an observed hidden/pagehide boundary. -Overlapping background events advance a generation so an older verification -cannot restore authority. Failed verification remains masked. Explicit host -revalidation/navigation and observed principal changes also fence operations and -replace the private query cache, including fast batched A→B→A transitions. -Cached permission is never substituted for a confirmed denial; denied references -are redacted. Genuine session boundaries do not transfer drafts, immutable edit -baselines or pending intents into a new authority generation. - -The original PR104 disable-on-blur/reopen design was superseded by this simpler -trigger model before review/merge. Stable wrappers and native disabled controls -remain useful for actual permission refreshes, but browser chrome focus alone -never activates those states. This is not a new inventory or IAM contract. - -Backend per-request authentication/authorization, submit-time exact permission -checks, after-await operation checks, and atomic UID/resourceVersion JSON Patch -tests remain required. A cookie/account change not yet observed by the host -cannot be detected atomically by this UI. Focus is not authentication, and this -change does not claim protection against an unobserved cookie transition between -requests. Observed host boundaries revoke pending work; backend checks protect -each dispatched request. Unknown dispatched outcomes are not reported as success. +### Session boundary: a change of signed-in user (implemented) + +The inventory treats a change of signed-in user, as the host observes it, as +the only session boundary. This matches the rest of staff-portal, whose pages +keep what they loaded and do not re-check the session on focus, tab switches or +loader revalidation. + +**Decision (2026-11-24).** The earlier design treated hiding the tab +(`visibilitychange` to hidden, `pagehide`) and every host loader revalidation as +session boundaries. On each one the page masked the inventory behind "Checking +inventory access…", re-ran the host loaders, discarded the private query cache +and read all nine collections again. In use this flashed on every return to the +tab and on host events such as a theme change, and it cancelled in-flight saves. +It protected nothing that per-request authorization does not already protect, +and its own documented limit was that an account change the host has not yet +observed cannot be detected by the UI. It was removed to match the host. + +What happens now: + +| Event | Inventory on screen | Private cache | Open forms and in-flight saves | +| --- | --- | --- | --- | +| Focus, blur, tab hidden or shown, `pagehide`/`pageshow` | Unchanged | Kept | Unchanged; a save in flight completes | +| Host loader revalidation, same user (for example a theme change) | Unchanged | Kept | New reads and operations pause while the loaders run; an in-flight save is refused with "No write was dispatched" and can be retried | +| Filter, record or tab change (presentation navigation) | Stays until the host finishes loading | Kept | Operations pause while the navigation is pending | +| Change of non-presentation URL parameters | Stays until the host finishes loading | Replaced | Ended | +| Change of signed-in user, including a fast A→B→A change | Replaced | Replaced, one fresh read | Ended; nothing transfers to the new user | +| Sign-out | Session expired state | Discarded | Ended | + +Retained protections: + +- One private QueryClient per signed-in user, never the host's shared client. +- The API authenticates and authorizes every request as the caller, through the + staff portal's caller-preserving proxy. +- Submit-time permission checks, after-await operation checks, and atomic + UID/resourceVersion JSON Patch tests on edits, so a stale page cannot + overwrite a changed record. +- 401 and 403 responses are handled where they occur: expired sessions and + denials are shown, and denied references are redacted from the view. +- Dispatched saves whose outcome is uncertain are reported as unknown, never as + success. + +A denial or permission change that happens while the page is idle is seen on the +next read or save, as on other staff-portal pages. Refresh inventory re-reads on +demand. ### Regression evidence and acceptance limits +The evidence below predates the 2026-11-24 session-boundary change. Statements +about hidden/pagehide masking, held pageshow restoration and background-return +checks describe removed behaviour; the tests for them were removed with it. + PR104's integration with feature-target revision `5b60656759033b61674ee202a9ad94f4d49f4a64` retains PR106's removal of provenance, Device source identity, component source references, reported-placement method @@ -622,8 +637,8 @@ Open `/session-fixture.html`. This mounts the actual inventory page and boundary under a synthetic host loader, not the preview bypass. API calls are handled in memory; writes return a synthetic failure and never reach an API. The console's `inventorySessionFixture` exposes `hold(boolean)`, `release()`, -`principal(string|null)`, `denied(boolean)`, and `stats()`. Blur/focus should do -nothing; pagehide followed by pageshow exercises held restoration. This harness +`principal(string|null)`, `denied(boolean)`, and `stats()`. Blur/focus and +pagehide/pageshow should do nothing; a principal change replaces the data. This harness is not a production build entry and is not evidence of real Safari acceptance. Read-only users browse without enabled writes. No-read and direct-link denials diff --git a/ui/provider/src/components/adversarial-review.test.tsx b/ui/provider/src/components/adversarial-review.test.tsx index bd83c7bf..33316f3a 100644 --- a/ui/provider/src/components/adversarial-review.test.tsx +++ b/ui/provider/src/components/adversarial-review.test.tsx @@ -137,17 +137,3 @@ it('must not silently advance an open edit form to a refreshed resourceVersion', await waitFor(() => expect(screen.getByRole('status')).toBeInTheDocument()); expect(patches).toEqual([]); }); - -it('must keep inventory concealed if foreground verification finishes after another pagehide', async () => { - let release: (() => void) | undefined; - let count = 0; - const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: async () => { if (++count === 2) await new Promise(resolve => { release = resolve; }); return { user: { metadata: { uid: 'staff-a' } } }; }, element: , children: [{ index: true, element: Private inventory label }] }]); - render(); - await screen.findByText('Private inventory label'); - fireEvent(window, new Event('pagehide')); - fireEvent(window, new Event('pageshow')); - await waitFor(() => expect(release).toBeDefined()); - fireEvent(window, new Event('pagehide')); - await act(async () => { release!(); }); - expect(screen.queryByText('Private inventory label')).not.toBeInTheDocument(); -}); diff --git a/ui/provider/src/components/device-placement-edit.test.tsx b/ui/provider/src/components/device-placement-edit.test.tsx index 8b041903..42d610ba 100644 --- a/ui/provider/src/components/device-placement-edit.test.tsx +++ b/ui/provider/src/components/device-placement-edit.test.tsx @@ -122,7 +122,7 @@ describe('reported location editor', () => { expect(screen.queryByDisplayValue('rack')).not.toBeInTheDocument(); expect(fetch).toHaveBeenCalledTimes(3); }); - it.each(['session', 'hidden', 'unmount', 'revalidation'])('revokes a delayed permission read on %s', async event => { + it.each(['session', 'unmount', 'revalidation'])('revokes a delayed permission read on %s', async event => { let resolve!: (value: unknown) => void; const fetch = vi.fn().mockImplementationOnce(() => new Promise(done => { resolve = done; })); vi.stubGlobal('fetch', fetch); @@ -150,7 +150,7 @@ describe('reported location editor', () => { expect(screen.getByRole('button', { name: 'Save changes' })).toBeDisabled(); expect(fetch).not.toHaveBeenCalled(); }); - it.each(['session', 'navigation', 'pagehide/pageshow'])('revokes a delayed reference read across %s', async event => { + it.each(['session', 'navigation'])('revokes a delayed reference read across %s', async event => { let resolve!: (value: unknown) => void; const fetch = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(device)).mockImplementationOnce(() => new Promise(done => { resolve = done; })); vi.stubGlobal('fetch', fetch); diff --git a/ui/provider/src/components/device-placement-edit.tsx b/ui/provider/src/components/device-placement-edit.tsx index 77296c06..b641762c 100644 --- a/ui/provider/src/components/device-placement-edit.tsx +++ b/ui/provider/src/components/device-placement-edit.tsx @@ -63,15 +63,8 @@ function DevicePlacementForm({ device, locations, issues }: { device: Device; lo return { ...previous, rack, facility: facility && visible.some(record => record.kind === 'Facility' && record.metadata.name === facility) ? facility : previous.facility }; }); useLayoutEffect(() => { - const invalidate = () => { scope.current.invalidate(); setBlocked(true); setBaseline(undefined); }; - const visibility = () => { if (document.visibilityState === 'hidden') invalidate(); }; - window.addEventListener('pagehide', invalidate); - document.addEventListener('visibilitychange', visibility); - return () => { - scope.current.invalidate(); - window.removeEventListener('pagehide', invalidate); - document.removeEventListener('visibilitychange', visibility); - }; + // Hiding the tab is not a session boundary; unmounting ends the operation. + return () => { scope.current.invalidate(); }; }, []); useLayoutEffect(() => { scope.current.invalidate(); diff --git a/ui/provider/src/components/exact-head-independent.test.tsx b/ui/provider/src/components/exact-head-independent.test.tsx index bb4a5607..26661f0a 100644 --- a/ui/provider/src/components/exact-head-independent.test.tsx +++ b/ui/provider/src/components/exact-head-independent.test.tsx @@ -22,14 +22,11 @@ async function open(editing: boolean, label: string) { fireEvent.change(screen.getByLabelText('Display name'), { target: { value: label } }); } -it.each([false, true].flatMap(strict => [false, true].flatMap(editing => ['review', 'dispatch-ok', 'dispatch-error'].flatMap(stage => ['fast-repeat', 'principal-repeat', 'slow', 'overlap', 'cancel-navigation', 'restore-hidden', 'restore-pagehide'].map(transition => ({ strict, editing, stage, transition }))))))('independent $transition $stage edit=$editing strict=$strict', async ({ strict, editing, stage, transition }) => { - const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible'); +it.each([false, true].flatMap(strict => [false, true].flatMap(editing => ['review', 'dispatch-ok', 'dispatch-error'].flatMap(stage => ['principal-repeat'].map(transition => ({ strict, editing, stage, transition }))))))('independent $transition $stage edit=$editing strict=$strict', async ({ strict, editing, stage, transition }) => { let principal = 'same-user'; let submitting = false; let intercepted = false; let releaseOperation: ((value: unknown) => void) | undefined; - let holdLoader = false; - const loaders: (() => void)[] = []; const writes: string[] = []; vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { const review = url.includes('selfsubjectaccessreviews'); @@ -41,47 +38,16 @@ it.each([false, true].flatMap(strict => [false, true].flatMap(editing => ['revie } return response(review ? { status: { allowed: true } } : original); })); - const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: async () => { - if (holdLoader) await new Promise(resolve => loaders.push(resolve)); - return { user: { metadata: { uid: principal } } }; - }, element: , children: [{ index: true, element: }] }]); + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: async () => ({ user: { metadata: { uid: principal } } }), element: , children: [{ index: true, element: }] }]); render(strict ? : ); await open(editing, 'Old input'); const submit = editing ? 'Save changes' : 'Create record'; submitting = true; fireEvent.click(screen.getByRole('button', { name: submit })); await waitFor(() => expect(releaseOperation).toBeDefined()); - if (transition === 'principal-repeat') { - await act(async () => { principal = 'other-user'; await router.revalidate(); principal = 'same-user'; await router.revalidate(); }); - } else if (transition === 'fast-repeat') { - await act(async () => { await router.revalidate(); await router.revalidate(); await router.revalidate(); }); - } else { - holdLoader = true; - act(() => { if (transition.startsWith('restore-')) { window.dispatchEvent(new Event('pagehide')); window.dispatchEvent(new Event('pageshow')); } else if (transition === 'cancel-navigation') void router.navigate('/?kind=Rack'); else void router.revalidate(); }); - await waitFor(() => expect(loaders).toHaveLength(1)); - expect(screen.queryByLabelText('Display name')).not.toBeInTheDocument(); - if (transition.startsWith('restore-')) { - if (transition === 'restore-hidden') { - visibility.mockReturnValue('hidden'); - fireEvent(document, new Event('visibilitychange')); - } else fireEvent(window, new Event('pagehide')); - await act(async () => loaders[0]()); - expect(screen.queryByLabelText('Display name')).not.toBeInTheDocument(); - expect(screen.queryByRole('button', { name: 'Create facility' })).not.toBeInTheDocument(); - holdLoader = false; - visibility.mockReturnValue('visible'); - await act(async () => window.dispatchEvent(new Event('pageshow'))); - } else if (transition === 'overlap' || transition === 'cancel-navigation') { - act(() => { if (transition === 'cancel-navigation') void router.navigate('/?kind=Facility'); else void router.revalidate(); }); - await waitFor(() => expect(loaders).toHaveLength(2)); - await act(async () => loaders[1]()); - await act(async () => loaders[0]()); - holdLoader = false; - } else { - await act(async () => loaders[0]()); - holdLoader = false; - } - } + // A→B→A user change ends on the same user but is still a session boundary: + // the pending operation must not complete into the new form. + await act(async () => { principal = 'other-user'; await router.revalidate(); principal = 'same-user'; await router.revalidate(); }); await open(editing, 'Fresh input'); await act(async () => releaseOperation!(response(stage === 'review' ? { status: { allowed: true } } : original, stage === 'dispatch-error' ? 503 : 200))); expect(writes).toHaveLength(stage === 'review' ? 0 : 1); @@ -93,14 +59,15 @@ it.each([false, true].flatMap(strict => [false, true].flatMap(editing => ['revie router.dispose(); }); -it.each([false, true].flatMap(strict => [401, 403, 404, 503].flatMap(status => ['revalidate', 'restore'].map(transition => ({ strict, status, transition })))))('late previous cache never overrides new denial $status strict=$strict via=$transition', async ({ strict, status, transition }) => { +it.each([false, true].flatMap(strict => [401, 403, 404, 503].map(status => ({ strict, status }))))('a late earlier refresh never overrides a newer denial $status strict=$strict', async ({ strict, status }) => { let phase = 'initial'; const releases: (() => void)[] = []; const freshRequests: string[] = []; const privateRecord = { ...original, spec: { ...original.spec, displayName: 'Private facility label' } }; vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { if (phase === 'denied') { - freshRequests.push(init.method!); + // Refresh also re-checks management permission (a SelfSubjectAccessReview POST, not a write). + if (!url.includes('selfsubjectaccessreviews')) freshRequests.push(init.method!); return response(undefined, status); } if (url.includes('selfsubjectaccessreviews')) return response({ status: { allowed: true } }); @@ -116,10 +83,7 @@ it.each([false, true].flatMap(strict => [401, 403, 404, 503].flatMap(status => [ fireEvent.click(screen.getByRole('button', { name: 'Refresh inventory' })); await waitFor(() => expect(releases).toHaveLength(9)); phase = 'denied'; - await act(async () => { - if (transition === 'restore') { fireEvent(window, new Event('pagehide')); fireEvent(window, new Event('pageshow')); } - else { await router.revalidate(); await router.revalidate(); } - }); + fireEvent.click(screen.getByRole('button', { name: 'Refresh inventory' })); const title = status === 401 ? 'Your session has expired' : status === 403 ? 'Inventory access needed' : status === 404 ? 'Inventory section unavailable' : 'Inventory is temporarily unavailable'; await screen.findByRole('heading', { name: title }); await act(async () => releases.forEach(release => release())); diff --git a/ui/provider/src/components/inventory-management-lifetime.test.tsx b/ui/provider/src/components/inventory-management-lifetime.test.tsx index e2cc6ea2..bae65740 100644 --- a/ui/provider/src/components/inventory-management-lifetime.test.tsx +++ b/ui/provider/src/components/inventory-management-lifetime.test.tsx @@ -10,7 +10,7 @@ const original = { ...inventoryPayload('Facility', values), metadata: { name: va const response = (data: unknown) => ({ ok: true, status: 200, json: async () => ({ data }) }); afterEach(() => vi.unstubAllGlobals()); -it.each(['create-pagehide', 'create-unmount', 'edit-pagehide', 'edit-unmount', 'create-dispatched-pagehide', 'edit-dispatched-pagehide'])('revokes pending authority on %s', async mode => { +it.each(['create-unmount', 'edit-unmount'])('revokes pending authority on %s', async mode => { let release: ((value: unknown) => void) | undefined; let reviews = 0; const writes: string[] = []; @@ -44,3 +44,45 @@ it.each(['create-pagehide', 'create-unmount', 'edit-pagehide', 'edit-unmount', ' expect(screen.getByRole('button', { name: editing ? 'Save changes' : 'Create record' })).toBeDisabled(); } }); + +it.each(['create', 'edit'])('%s: hiding the tab mid-save leaves the form and the save alone', async mode => { + let release: ((value: unknown) => void) | undefined; + let reviews = 0; + const writes: string[] = []; + vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { + if (url.includes('selfsubjectaccessreviews')) { + if (++reviews === 2) return new Promise(resolve => { release = resolve; }); + return response({ status: { allowed: true } }); + } + if (init.method !== 'GET') writes.push(init.method!); + return response(original); + })); + const editing = mode === 'edit'; + render(); + fireEvent.click(await findEnabledButton({ name: editing ? 'Edit display name' : 'Create facility' })); + if (!editing) fireEvent.change(screen.getByLabelText('Record name'), { target: { value: values.name } }); + fireEvent.change(screen.getByLabelText('Display name'), { target: { value: 'Kept across tab switch' } }); + fireEvent.click(screen.getByRole('button', { name: editing ? 'Save changes' : 'Create record' })); + await waitFor(() => expect(release).toBeDefined()); + const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden'); + fireEvent(document, new Event('visibilitychange')); + fireEvent(window, new Event('pagehide')); + visibility.mockReturnValue('visible'); + fireEvent(document, new Event('visibilitychange')); + fireEvent(window, new Event('pageshow')); + await act(async () => { release!(response({ status: { allowed: true } })); }); + await screen.findByText(editing ? 'Display name saved.' : 'Facility created.'); + expect(writes).toEqual([editing ? 'PATCH' : 'POST']); + visibility.mockRestore(); +}); + +it('shows no "checking access" text while the management permission is being checked', async () => { + let allow: ((value: unknown) => void) | undefined; + vi.stubGlobal('fetch', vi.fn(() => new Promise(resolve => { allow = resolve; }))); + render(); + await waitFor(() => expect(allow).toBeDefined()); + expect(screen.getByRole('button', { name: 'Create facility' })).toBeDisabled(); + expect(screen.getByRole('status')).toBeEmptyDOMElement(); + await act(async () => allow!(response({ status: { allowed: true } }))); + await findEnabledButton({ name: 'Create facility' }); +}); diff --git a/ui/provider/src/components/inventory-management.tsx b/ui/provider/src/components/inventory-management.tsx index 75ed07bb..5c7c8db8 100644 --- a/ui/provider/src/components/inventory-management.tsx +++ b/ui/provider/src/components/inventory-management.tsx @@ -44,15 +44,13 @@ function InventoryManagementForm({ kind, record, facilities: sourceFacilities, c useLayoutEffect(() => { const current = new InventoryOperationScope(); scope.current = current; - const invalidate = () => { scope.current.invalidate(); setBaseline(undefined); setBlocked(true); }; - const visibility = () => { if (document.visibilityState === 'hidden') invalidate(); }; - window.addEventListener('pagehide', invalidate); - document.addEventListener('visibilitychange', visibility); + // Hiding the tab is not a session boundary (see inventory-session-boundary): + // the form and any save in progress carry on. Unmounting ends them. return () => { - invalidate(); + scope.current.invalidate(); + setBaseline(undefined); + setBlocked(true); started.current = false; - window.removeEventListener('pagehide', invalidate); - document.removeEventListener('visibilitychange', visibility); }; }, []); const [baseline, setBaseline] = useState(); diff --git a/ui/provider/src/components/inventory-navigation-safety.test.tsx b/ui/provider/src/components/inventory-navigation-safety.test.tsx index 37ad1352..e197e409 100644 --- a/ui/provider/src/components/inventory-navigation-safety.test.tsx +++ b/ui/provider/src/components/inventory-navigation-safety.test.tsx @@ -70,8 +70,18 @@ it.each([false, true].flatMap(editing => ['navigation', 'revalidation'].map(tran if (transition === 'revalidation') await router.revalidate(); else await router.navigate('/?kind=Facility&name=independent-review'); }); - await open(editing); - await act(async () => release!(response({ status: { allowed: true } }))); + if (transition === 'revalidation') { + // A host revalidation leaves the open form in place; the save that was in + // flight is refused without a write, and the form is reopened to retry. + await act(async () => release!(response({ status: { allowed: true } }))); + expect(writes).toEqual([]); + await screen.findByText(/No write was dispatched/); + fireEvent.click(screen.getByRole('button', { name: 'Cancel' })); + await open(editing); + } else { + await open(editing); + await act(async () => release!(response({ status: { allowed: true } }))); + } expect(writes).toEqual([]); expect(screen.queryByText(/Display name saved\.|Facility created\./)).not.toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: editing ? 'Save changes' : 'Create record' })); diff --git a/ui/provider/src/components/inventory-session-boundary.test.tsx b/ui/provider/src/components/inventory-session-boundary.test.tsx index 6c814f52..6155fe35 100644 --- a/ui/provider/src/components/inventory-session-boundary.test.tsx +++ b/ui/provider/src/components/inventory-session-boundary.test.tsx @@ -123,77 +123,35 @@ describe('host inventory session isolation', () => { router.dispose(); }); - it('keeps failed foreground restoration masked until the next restoration succeeds', async () => { - const router = await mountHost(() => ({ user: { metadata: { uid: 'staff-a' } } }), 'Private inventory'); - await screen.findByText('Private inventory'); - let release!: () => void; - const revalidate = vi.spyOn(router, 'revalidate').mockRejectedValueOnce(new Error('verification failed')).mockImplementationOnce(() => new Promise(resolve => { release = resolve; })); + it.each(['revalidation', 'hidden', 'pagehide'])('keeps inventory, reads and operation authority through a same-user %s, like other staff-portal pages', async event => { + let scope: InventoryOperationScope | undefined; + const inventoryRead = vi.fn(async () => 'Visible inventory'); + function Records() { + scope = useContext(InventoryOperationContext); + const query = useQuery({ queryKey: ['inventory'], queryFn: inventoryRead, staleTime: Infinity }); + return

{query.data ?? 'Empty inventory cache'}

; + } + const loader = vi.fn(() => ({ user: { metadata: { uid: 'staff-a' } } })); + const router = await mountHost(loader, ); + await screen.findByText('Visible inventory'); + const pending = scope!.begin(); + const visibility = vi.spyOn(document, 'visibilityState', 'get'); await act(async () => { - fireEvent(window, new Event('pagehide')); - fireEvent(window, new Event('pageshow')); - }); - expect(revalidate).toHaveBeenCalledTimes(1); - await waitFor(() => expect(screen.queryByText('Private inventory')).not.toBeInTheDocument()); - fireEvent(window, new Event('pagehide')); - fireEvent(window, new Event('pageshow')); - await waitFor(() => expect(release).toBeDefined()); - expect(revalidate).toHaveBeenCalledTimes(2); - expect(screen.queryByText('Private inventory')).not.toBeInTheDocument(); - await act(async () => release()); - await screen.findByText('Private inventory'); - router.dispose(); - }); - - it.each(['logout', 'failure'])('clears private data when foreground restoration observes %s', async outcome => { - let expired = false; - const loader = vi.fn(() => { - if (expired && outcome === 'failure') throw new Response('Synthetic failure', { status: 503 }); - if (expired) return { user: null }; - return { user: { metadata: { uid: 'staff-a' } } }; + if (event === 'revalidation') await router.revalidate(); + else if (event === 'hidden') { visibility.mockReturnValue('hidden'); fireEvent(document, new Event('visibilitychange')); visibility.mockReturnValue('visible'); fireEvent(document, new Event('visibilitychange')); } + else { fireEvent(window, new Event('pagehide')); fireEvent(window, new Event('pageshow')); } }); - const router = await mountHost(loader, 'Visible inventory'); expect(screen.getByText('Visible inventory')).toBeInTheDocument(); - expect(loader).toHaveBeenCalledTimes(1); - expired = true; - await act(async () => { - fireEvent(window, new Event('pagehide')); - fireEvent(window, new Event('pageshow')); - }); - await waitFor(() => { - expect(loader).toHaveBeenCalledTimes(2); - expect(router.state.revalidation).toBe('idle'); - if (outcome === 'logout') expect(router.state.loaderData['layouts/milo.layout']).toEqual({ user: null }); - else expect(router.state.errors).not.toBeNull(); - expect(screen.queryByText('Visible inventory')).not.toBeInTheDocument(); - }); - router.dispose(); + expect(screen.queryByText('Empty inventory cache')).not.toBeInTheDocument(); + expect(inventoryRead).toHaveBeenCalledTimes(1); + expect(loader).toHaveBeenCalledTimes(event === 'revalidation' ? 2 : 1); + // A host revalidation may be a change of user, so an operation started + // before it is fenced; new operations start normally afterwards. + if (event === 'revalidation') expect(() => pending.assertCurrent()).toThrow(InventoryOperationInvalidated); + else expect(() => pending.assertCurrent()).not.toThrow(); + expect(() => scope!.begin().assertCurrent()).not.toThrow(); }); - it('discards genuine hidden data and waits for visible verification before a fresh read', async () => { - const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible'); - let release: (() => void) | undefined; - let reads = 0; - const inventoryRead = vi.fn(async () => 'Private inventory'); - function Records() { - const query = useQuery({ queryKey: ['inventory'], queryFn: inventoryRead, staleTime: Infinity }); - return

{query.data}

; - } - await mountHost(async () => { - if (++reads > 1) await new Promise(resolve => { release = resolve; }); - return { user: { metadata: { uid: 'staff-a' } } }; - }, ); - await screen.findByText('Private inventory'); - visibility.mockReturnValue('hidden'); - fireEvent(document, new Event('visibilitychange')); - expect(screen.queryByText('Private inventory')).not.toBeInTheDocument(); - visibility.mockReturnValue('visible'); - fireEvent(document, new Event('visibilitychange')); - await waitFor(() => expect(release).toBeDefined()); - expect(screen.queryByText('Private inventory')).not.toBeInTheDocument(); - await act(async () => release!()); - await screen.findByText('Private inventory'); - expect(inventoryRead).toHaveBeenCalledTimes(2); - }); it('fails closed outside the authenticated host unless explicitly previewing', () => { render(Restricted inventory); expect(screen.queryByText('Restricted inventory')).not.toBeInTheDocument(); @@ -206,7 +164,7 @@ describe('host inventory session isolation', () => { expect(screen.queryByText('Restricted inventory')).not.toBeInTheDocument(); }); - it('isolates identical query keys across principal changes and pending revalidation', async () => { + it('isolates identical query keys across a principal change confirmed by the host', async () => { let principal = 'staff-a'; let release: (() => void) | undefined; const read = vi.fn(async () => `Inventory for ${principal}`); @@ -222,48 +180,12 @@ describe('host inventory session isolation', () => { principal = 'staff-b'; let completion: Promise; act(() => { completion = router.revalidate(); }); - await waitFor(() => expect(screen.queryByText('Inventory for staff-a')).not.toBeInTheDocument()); + // Like host pages, the current view stays until the host confirms the new user. + await waitFor(() => expect(release).toBeDefined()); await act(async () => { release?.(); await completion; }); await screen.findByText('Inventory for staff-b'); expect(read).toHaveBeenCalledTimes(2); expect(screen.queryByText('Inventory for staff-a')).not.toBeInTheDocument(); }); - it('hides background data and revalidates the actual host loader before restoring it', async () => { - const loader = vi.fn(() => ({ user: { metadata: { uid: 'staff-a' } } })); - await mountHost(loader, 'Restricted inventory'); - await screen.findByText('Restricted inventory'); - const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden'); - fireEvent(document, new Event('visibilitychange')); - expect(screen.queryByText('Restricted inventory')).not.toBeInTheDocument(); - loader.mockReturnValue({ user: null } as never); - visibility.mockReturnValue('visible'); - fireEvent(document, new Event('visibilitychange')); - await screen.findByText('Your session has expired'); - expect(loader).toHaveBeenCalledTimes(2); - expect(screen.queryByText('Restricted inventory')).not.toBeInTheDocument(); - }); - - it('only restores the newest foreground generation after successive pagehide and pageshow events', async () => { - const releases: (() => void)[] = []; - let reads = 0; - const router = await mountHost(async () => { - if (++reads > 1) await new Promise(resolve => releases.push(resolve)); - return { user: { metadata: { uid: 'staff-a' } } }; - }, 'Private inventory'); - await screen.findByText('Private inventory'); - fireEvent(window, new Event('pagehide')); - fireEvent(window, new Event('pageshow')); - await waitFor(() => expect(releases).toHaveLength(1)); - fireEvent(window, new Event('pagehide')); - fireEvent(window, new Event('pageshow')); - await waitFor(() => expect(releases).toHaveLength(2)); - await act(async () => releases[0]()); - expect(screen.queryByText('Private inventory')).not.toBeInTheDocument(); - await act(async () => releases[1]()); - await screen.findByText('Private inventory'); - expect(reads).toBe(3); - expect(router.state.revalidation).toBe('idle'); - router.dispose(); - }); }); diff --git a/ui/provider/src/components/inventory-session-boundary.tsx b/ui/provider/src/components/inventory-session-boundary.tsx index 3e47c442..52c8725c 100644 --- a/ui/provider/src/components/inventory-session-boundary.tsx +++ b/ui/provider/src/components/inventory-session-boundary.tsx @@ -1,6 +1,6 @@ import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import { UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, useLocation, useNavigation, useRevalidator, useRouteLoaderData, type Location } from 'react-router'; +import { UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, useLocation, useNavigation, useRouteLoaderData, type Location } from 'react-router'; import { InventoryAccessState } from './inventory-access-state'; import { LoadingState } from './states'; import { InventoryOperationContext, InventoryOperationGenerationContext, InventoryOperationReadyContext, InventoryOperationScope } from '../lib/inventory-operation'; @@ -8,6 +8,23 @@ import { InventoryReadContext, InventoryReadScope } from '../lib/inventory-read' export const InventoryPreviewContext = createContext(false); +type MiloLayout = { user?: { metadata?: { uid?: string; name?: string } } } | undefined; +const principalOf = (loaderData: Record) => { + const identity = loaderData['layouts/milo.layout'] as MiloLayout; + return identity?.user?.metadata?.uid ?? identity?.user?.metadata?.name; +}; + +/** + * A private query cache and operation/read scopes for one signed-in user. + * + * The session boundary is a change of signed-in user (or sign-out), as the + * host observes it, and nothing else. Like the rest of staff-portal, hiding the + * tab, focus changes and host loader revalidation (for example a theme change) + * leave loaded inventory and open forms alone; the API authorizes every request + * and edits carry UID/resourceVersion preconditions. Operations are fenced while + * a navigation is pending; operations and new reads pause while the host + * re-runs its loaders; neither changes what is on screen. + */ export function SessionQueries({ children, principal, authority, generation }: { children: ReactNode; principal: string; authority: boolean; generation: number }) { const [client] = useState(() => new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0, refetchOnWindowFocus: false } } })); const [scope] = useState(() => new InventoryOperationScope()); @@ -15,129 +32,66 @@ export function SessionQueries({ children, principal, authority, generation }: { const ready = authority; const host = useContext(UNSAFE_DataRouterContext); useLayoutEffect(() => { - const identity = host?.router.state.loaderData['layouts/milo.layout'] as { user?: { metadata?: { uid?: string; name?: string } } } | undefined; - if (ready && host?.router.state.revalidation === 'idle' && host.router.state.navigation.state === 'idle' && (identity?.user?.metadata?.uid ?? identity?.user?.metadata?.name) === principal) scope.startLifecycle(); - else scope.invalidate(); const invalidate = () => { scope.invalidate(); reads.suspend(); void client.cancelQueries(); }; - if (authority && host?.router.state.revalidation === 'idle' && host.router.state.navigation.state === 'idle' && (identity?.user?.metadata?.uid ?? identity?.user?.metadata?.name) === principal) reads.resume(); - else invalidate(); - const visibility = () => { if (document.visibilityState === 'hidden') invalidate(); }; - window.addEventListener('pagehide', invalidate); - document.addEventListener('visibilitychange', visibility); + const current = !host || principalOf(host.router.state.loaderData) === principal; + if (current) reads.resume(); else invalidate(); + if (ready && current) scope.startLifecycle(); else scope.invalidate(); + // While the host re-runs its loaders the signed-in user may be changing, so + // saves and new reads are paused; what is on screen stays. Afterwards, if + // the user is the same, reads resume and new operations may start. + let revalidating = false; const unsubscribe = host?.router.subscribe(state => { - const identity = state.loaderData['layouts/milo.layout'] as { user?: { metadata?: { uid?: string; name?: string } } } | undefined; - if (state.revalidation !== 'idle' || state.navigation.state !== 'idle' || (identity?.user?.metadata?.uid ?? identity?.user?.metadata?.name) !== principal) invalidate(); + if (principalOf(state.loaderData) !== principal) { invalidate(); return; } + if (state.revalidation !== 'idle') { revalidating = true; scope.invalidate(); reads.suspend(); } + else if (revalidating) { revalidating = false; reads.resume(); if (ready) scope.startLifecycle(); } }); - return () => { - invalidate(); unsubscribe?.(); - window.removeEventListener('pagehide', invalidate); - document.removeEventListener('visibilitychange', visibility); - }; - }, [host, principal, scope, ready, generation, authority, reads, client]); + return () => { invalidate(); unsubscribe?.(); }; + }, [host, principal, scope, ready, generation, reads, client]); useEffect(() => () => client.clear(), [client]); return {children}; } -function isPresentationNavigation(current: Location, next: Location | undefined) { - if (!next || current.pathname !== next.pathname || current.search === next.search) return false; - const currentParams = new URLSearchParams(current.search); - const nextParams = new URLSearchParams(next.search); - for (const key of ['kind', 'record', 'namespace', 'q', 'location', 'model', 'tab', 'view', 'selectedKind', 'selected']) { - currentParams.delete(key); - nextParams.delete(key); - } - return currentParams.toString() === nextParams.toString(); +/** URL parameters that only change what is shown, never whose data or which scope. */ +const PRESENTATION_PARAMS = ['kind', 'record', 'namespace', 'q', 'location', 'model', 'tab', 'view', 'selectedKind', 'selected']; + +/** The page and any non-presentation parameters: a change of these starts a fresh cache. */ +function dataScope(location: Pick) { + const params = new URLSearchParams(location.search); + for (const key of PRESENTATION_PARAMS) params.delete(key); + return `${location.pathname}?${params.toString()}`; } function HostedInventory({ children, retainPresentationData = false, pending: pendingContent = , unavailable = status => }: { children: ReactNode; retainPresentationData?: boolean; pending?: ReactNode; unavailable?: (status: number) => ReactNode }) { const host = useContext(UNSAFE_DataRouterContext); + const identity = useRouteLoaderData('layouts/milo.layout') as MiloLayout; + const principal = identity?.user?.metadata?.uid ?? identity?.user?.metadata?.name; + // The private cache is keyed by the signed-in user, so a change of user + // remounts it. A fast A→B→A change can reach render as "still A"; the + // subscription catches that case, and only that case, so an ordinary change + // of user remounts once. + const rendered = useRef(principal); + rendered.current = principal; const [sessionGeneration, setSessionGeneration] = useState(0); - const [operationGeneration, setOperationGeneration] = useState(0); useLayoutEffect(() => { if (!host) return; - const readPrincipal = (state: typeof host.router.state) => { - const identity = state.loaderData['layouts/milo.layout'] as { user?: { metadata?: { uid?: string; name?: string } } } | undefined; - return identity?.user?.metadata?.uid ?? identity?.user?.metadata?.name; - }; - let observedPrincipal = readPrincipal(host.router.state); - let pending = host.router.state.revalidation !== 'idle' || host.router.state.navigation.state !== 'idle'; - let resetAfterPending = pending; + let observed = principalOf(host.router.state.loaderData); return host.router.subscribe(state => { - const nextPrincipal = readPrincipal(state); - if (nextPrincipal !== observedPrincipal) { - observedPrincipal = nextPrincipal; - setSessionGeneration(current => current + 1); - } - if (state.revalidation !== 'idle' || state.navigation.state !== 'idle') { - pending = true; - if (!retainPresentationData || state.revalidation !== 'idle' || state.navigation.formMethod || !isPresentationNavigation(state.location, state.navigation.location)) resetAfterPending = true; - } else if (pending) { - pending = false; - setOperationGeneration(current => current + 1); - if (resetAfterPending) setSessionGeneration(current => current + 1); - resetAfterPending = false; - } + const next = principalOf(state.loaderData); + if (next === observed) return; + observed = next; + if (next === rendered.current) setSessionGeneration(current => current + 1); }); - }, [host, retainPresentationData]); - const identity = useRouteLoaderData('layouts/milo.layout') as { user?: { metadata?: { uid?: string; name?: string } } } | undefined; - const principal = identity?.user?.metadata?.uid ?? identity?.user?.metadata?.name; + }, [host]); const location = useLocation(); const navigation = useNavigation(); - const revalidator = useRevalidator(); - const revalidate = useRef(revalidator.revalidate); - revalidate.current = revalidator.revalidate; - const [checking, setChecking] = useState(() => typeof document !== 'undefined' && document.visibilityState === 'hidden'); - const [failed, setFailed] = useState(false); - const generation = useRef(0); - useEffect(() => { - let active = true; - let awaitingReturn = document.visibilityState === 'hidden'; - const hide = () => { - generation.current++; - awaitingReturn = true; - setChecking(true); - }; - const verify = () => { - if (!awaitingReturn || document.visibilityState === 'hidden') return; - awaitingReturn = false; - const attempt = ++generation.current; - setFailed(false); - let succeeded = true; - void revalidate.current().catch(() => { - succeeded = false; - if (active && attempt === generation.current) { - setChecking(true); - setFailed(true); - } - }).finally(() => { - if (active && attempt === generation.current && document.visibilityState !== 'hidden') { - setChecking(!succeeded); - } - }); - }; - const visibility = () => document.visibilityState === 'hidden' ? hide() : verify(); - window.addEventListener('pagehide', hide); - window.addEventListener('pageshow', verify); - document.addEventListener('visibilitychange', visibility); - return () => { - active = false; - generation.current++; - window.removeEventListener('pagehide', hide); - window.removeEventListener('pageshow', verify); - document.removeEventListener('visibilitychange', visibility); - }; - }, []); - if (failed) return unavailable(503); - const presentationPending = retainPresentationData && !navigation.formMethod && isPresentationNavigation(location, navigation.location); - if (checking || revalidator.state !== 'idle' || navigation.state !== 'idle' && !presentationPending) return <>{pendingContent}; - if (!principal) return unavailable(401); - // During a presentation navigation the location has not changed yet, so the children are the page - // already on screen; keep it while the host verifies, with writes withheld until it is idle. - return {navigation.state !== 'idle' && !presentationPending ? pendingContent : children}; + // Like host pages, the current view stays on screen while the host loads the + // next one. Without a signed-in user nothing private is rendered. + if (!principal) return navigation.state !== 'idle' ? <>{pendingContent} : unavailable(401); + return {children}; } export function InventorySessionBoundary({ children, retainPresentationData, pending, unavailable }: { children: ReactNode; retainPresentationData?: boolean; pending?: ReactNode; unavailable?: (status: number) => ReactNode }) { diff --git a/ui/provider/src/components/inventory-stable-controls.test.tsx b/ui/provider/src/components/inventory-stable-controls.test.tsx index 715ad8bf..23339acd 100644 --- a/ui/provider/src/components/inventory-stable-controls.test.tsx +++ b/ui/provider/src/components/inventory-stable-controls.test.tsx @@ -102,7 +102,7 @@ it.each(cases.flatMap(test => [false, true].flatMap(strict => [false, true].map( view.router.dispose(); }); -it.each(['denied', 'principal', 'hidden', 'pagehide'])('removes retained private drafts on confirmed %s', async transition => { +it.each(['principal'])('removes retained private drafts on confirmed %s', async transition => { const view = host(); fireEvent.click(await findEnabledButton({ name: 'Create facility' })); fireEvent.change(screen.getByLabelText('Display name'), { target: { value: 'Private draft' } }); diff --git a/ui/provider/src/components/inventory-tab-navigation.test.tsx b/ui/provider/src/components/inventory-tab-navigation.test.tsx index 097cdf54..e7959473 100644 --- a/ui/provider/src/components/inventory-tab-navigation.test.tsx +++ b/ui/provider/src/components/inventory-tab-navigation.test.tsx @@ -298,42 +298,25 @@ it('restarts management authority after immediate same-principal host navigation view.router.dispose(); }); -it.each(['principal', 'logout', 'denial', 'hidden', 'pagehide', 'revalidation', 'unknown-query'])('retains only static chrome across a real %s boundary', async transition => { +it.each(['principal', 'logout', 'denial', 'unknown-query'])('replaces private data after a real %s boundary', async transition => { const view = host(); await screen.findByRole('searchbox', { name: 'Search devices' }); const navigation = screen.getByRole('navigation', { name: 'Inventory categories' }); - view.hold(); - if (transition === 'principal') view.principal('staff-b'); - if (transition === 'logout') view.principal(null); - if (transition === 'denial') view.deny(); - if (transition === 'hidden') { - const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden'); - fireEvent(document, new Event('visibilitychange')); - expect(screen.queryByText('Example compute server')).not.toBeInTheDocument(); - visibility.mockReturnValue('visible'); - fireEvent(document, new Event('visibilitychange')); - } else if (transition === 'pagehide') { - fireEvent(window, new Event('pagehide')); - expect(screen.queryByText('Example compute server')).not.toBeInTheDocument(); - fireEvent(window, new Event('pageshow')); - } else if (transition === 'principal' || transition === 'logout') { - fireEvent.click(within(navigation).getByRole('tab', { name: 'Locations' })); - } else if (transition === 'unknown-query') { - act(() => { void view.router.navigate('?kind=Device&scope=other'); }); - } else act(() => { void view.router.revalidate(); }); - if (transition === 'principal' || transition === 'logout') { - // A tab click is a presentation navigation: the page already on screen stays while the host checks, - // nothing new is shown, and the check's answer (another user, or none) clears it when it returns. - await waitFor(() => expect(view.router.state.navigation.state).toBe('loading')); - expect(screen.queryByText('Checking inventory access…')).not.toBeInTheDocument(); - expect(view.router.state.location.search).not.toContain('kind=Site'); + if (transition === 'denial') { + // A denial is observed on the next read, here an explicit refresh. + await waitFor(() => expect(screen.getByRole('button', { name: 'Refresh inventory' })).toBeEnabled()); + view.deny(); + fireEvent.click(screen.getByRole('button', { name: 'Refresh inventory' })); } else { - await screen.findByText('Checking inventory access…'); - expect(screen.queryByText('Example compute server')).not.toBeInTheDocument(); - expect(navigation.textContent).not.toMatch(/\d/); + view.hold(); + if (transition === 'principal') view.principal('staff-b'); + if (transition === 'logout') view.principal(null); + if (transition === 'unknown-query') act(() => { void view.router.navigate('?kind=Device&scope=other'); }); + else fireEvent.click(within(navigation).getByRole('tab', { name: 'Locations' })); + await waitFor(() => expect(view.router.state.navigation.state).toBe('loading')); + expect(screen.getByRole('navigation', { name: 'Inventory categories' })).toBe(navigation); + await view.release(); } - expect(screen.getByRole('navigation', { name: 'Inventory categories' })).toBe(navigation); - await view.release(); if (transition === 'logout') { await screen.findByText('Your session has expired'); expect(view.collections).toHaveBeenCalledTimes(9); @@ -343,7 +326,7 @@ it.each(['principal', 'logout', 'denial', 'hidden', 'pagehide', 'revalidation', expect(view.collections).toHaveBeenCalledTimes(18); } else { await screen.findByRole('searchbox'); - expect(view.collections).toHaveBeenCalledTimes(18); + await waitFor(() => expect(view.collections).toHaveBeenCalledTimes(18)); } expect(view.writes).not.toHaveBeenCalled(); view.router.dispose(); diff --git a/ui/provider/src/components/inventory-visible-focus-save.test.tsx b/ui/provider/src/components/inventory-visible-focus-save.test.tsx index 3b5e2fee..26ecd1e6 100644 --- a/ui/provider/src/components/inventory-visible-focus-save.test.tsx +++ b/ui/provider/src/components/inventory-visible-focus-save.test.tsx @@ -15,7 +15,7 @@ const device = { ...fixturePhysicalDevices[0], metadata, spec: { ...fixturePhysi const response = (data: unknown) => ({ ok: true, status: 200, json: async () => ({ data }) }); afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); }); -it.each(['create', 'label', 'location'].flatMap(mode => ['review', 'read', 'dispatch'].filter(stage => mode !== 'create' || stage !== 'read').flatMap(stage => ['focus', 'hidden', 'principal'].map(transition => ({ mode, stage, transition })))))('$transition handles pending $mode $stage without transferring authority', async ({ mode, stage, transition }) => { +it.each(['create', 'label', 'location'].flatMap(mode => ['review', 'read', 'dispatch'].filter(stage => mode !== 'create' || stage !== 'read').flatMap(stage => ['focus', 'principal'].map(transition => ({ mode, stage, transition })))))('$transition handles pending $mode $stage without transferring authority', async ({ mode, stage, transition }) => { let release: (() => void) | undefined; let reviews = 0; let held = false; diff --git a/ui/provider/src/components/pr103-review-negatives.test.tsx b/ui/provider/src/components/pr103-review-negatives.test.tsx index e7a30151..a8a4f2c3 100644 --- a/ui/provider/src/components/pr103-review-negatives.test.tsx +++ b/ui/provider/src/components/pr103-review-negatives.test.tsx @@ -35,57 +35,3 @@ it.each([false, true])('does not publish new-principal reads while explicit host expect(requests).toHaveBeenCalledTimes(before); router.dispose(); }); - -it.each(['revalidate', 'overlap', 'hidden', 'denied'])('renews management only after a genuine boundary and fresh successful read: %s', async scenario => { - let holding = false; - let denied = false; - const releases: (() => void)[] = []; - const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible'); - const record = inventoryPayload('Facility', { name: 'fresh', namespace: 'default', displayName: 'Synthetic fresh facility', facility: '', height: '' }); - vi.stubGlobal('fetch', vi.fn(async (url: string) => { - if (url.includes('selfsubjectaccessaccessreviews')) throw new Error('invalid endpoint'); - if (url.includes('selfsubjectaccessreviews')) return response({ status: { allowed: true } }); - if (denied) return { ok: false, status: 403, json: async () => ({ error: 'synthetic' }) }; - return response({ items: url.includes('/facilities?') ? [record] : [] }); - })); - const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: async () => { - if (holding) await new Promise(resolve => releases.push(resolve)); - return { user: { metadata: { uid: 'staff-a' } } }; - }, element: , children: [{ index: true, element: }] }], { initialEntries: ['/?kind=Facility'] }); - render(); - await findEnabledButton({ name: 'Create facility' }); - const table = screen.getByRole('table'); - fireEvent.click(screen.getByRole('button', { name: 'Create facility' })); - fireEvent.change(screen.getByLabelText('Display name'), { target: { value: 'Abandoned old form' } }); - holding = true; - if (scenario === 'hidden') { - visibility.mockReturnValue('hidden'); - fireEvent(document, new Event('visibilitychange')); - expect(screen.queryByRole('table')).not.toBeInTheDocument(); - visibility.mockReturnValue('visible'); - fireEvent(document, new Event('visibilitychange')); - } else act(() => { void router.revalidate(); }); - await waitFor(() => expect(releases).toHaveLength(1)); - expect(screen.queryByLabelText('Display name')).not.toBeInTheDocument(); - if (scenario === 'overlap') { - act(() => { void router.revalidate(); }); - await waitFor(() => expect(releases).toHaveLength(2)); - await act(async () => releases[0]()); - expect(screen.getByRole('button', { name: 'Create facility' })).toBeDisabled(); - } - denied = scenario === 'denied'; - await act(async () => releases.at(-1)!()); - if (denied) { - await screen.findByRole('heading', { name: 'Inventory access needed' }); - expect(screen.getByRole('button', { name: 'Create facility' })).toBeDisabled(); - denied = false; - holding = false; - act(() => { void router.revalidate(); }); - } - await waitFor(() => expect(screen.getByRole('button', { name: 'Create facility' })).toBeEnabled()); - expect(screen.getByRole('table')).not.toBe(table); - fireEvent.click(screen.getByRole('button', { name: 'Create facility' })); - expect(screen.getByLabelText('Display name')).toHaveValue(''); - router.dispose(); - visibility.mockRestore(); -}); diff --git a/ui/provider/src/components/reviewer-exact-staging.test.tsx b/ui/provider/src/components/reviewer-exact-staging.test.tsx index 38f04366..1e044291 100644 --- a/ui/provider/src/components/reviewer-exact-staging.test.tsx +++ b/ui/provider/src/components/reviewer-exact-staging.test.tsx @@ -14,34 +14,6 @@ const device = { ...fixturePhysicalDevices[0], metadata, spec: { ...fixturePhysi const response = (data: unknown, status = 200) => ({ ok: status < 400, status, json: async () => ({ data }) }); afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); }); -it('settled host keeps earlier foreground generations masked until the newest loader finishes', async () => { - const releases: (() => void)[] = []; - let reads = 0; - const loader = vi.fn(async () => { - if (++reads > 1) await new Promise(resolve => releases.push(resolve)); - return { user: { metadata: { uid: 'synthetic-staff' } } }; - }); - const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader, element: , children: [{ index: true, element: Private generation inventory }] }]); - await act(async () => { render(); }); - await screen.findByText('Private generation inventory'); - await act(async () => {}); - for (const expectedReads of [1, 2]) { - await act(async () => { - fireEvent(window, new Event('pagehide')); - fireEvent(window, new Event('pageshow')); - }); - await waitFor(() => expect(releases).toHaveLength(expectedReads)); - expect(screen.queryByText('Private generation inventory')).not.toBeInTheDocument(); - } - await act(async () => releases[0]()); - expect(screen.queryByText('Private generation inventory')).not.toBeInTheDocument(); - await act(async () => releases[1]()); - await screen.findByText('Private generation inventory'); - expect(router.state.revalidation).toBe('idle'); - expect(loader).toHaveBeenCalledTimes(3); - router.dispose(); -}); - it.each(['label', 'location'].flatMap(mode => [401, 403, 404, 409, 422, 503, 0].map(status => ({ mode, status }))))('held $mode PATCH keeps visible focus inert then handles terminal $status', async ({ mode, status }) => { let rejectWrite: (() => void) | undefined; const original = mode === 'location' ? device : facility; @@ -101,49 +73,3 @@ it.each(['label', 'location'].flatMap(mode => [401, 403, 404, 409, 422, 503, 0]. } router.dispose(); }); - -it.each(['logout', 'failure'].flatMap(outcome => ['pagehide', 'hidden'].flatMap(transition => ['immediate', 'held'].map(timing => ({ outcome, transition, timing })))))('settled host $transition restoration handles $timing $outcome', async ({ outcome, transition, timing }) => { - let expired = false; - let release: (() => void) | undefined; - const loader = vi.fn(async () => { - if (!expired) return { user: { metadata: { uid: 'synthetic-staff' } } }; - if (timing === 'held') await new Promise(resolve => { release = resolve; }); - if (outcome === 'failure') throw new Response('Synthetic failure', { status: 503 }); - return { user: null }; - }); - const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader, element: , errorElement:

Host failure

, children: [{ index: true, element: Private review inventory }] }]); - await act(async () => { render(); }); - await screen.findByText('Private review inventory'); - await act(async () => {}); - expired = true; - const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible'); - await act(async () => { - if (transition === 'hidden') { - visibility.mockReturnValue('hidden'); - fireEvent(document, new Event('visibilitychange')); - } else fireEvent(window, new Event('pagehide')); - }); - expect(screen.queryByText('Private review inventory')).not.toBeInTheDocument(); - await act(async () => { - if (transition === 'hidden') { - visibility.mockReturnValue('visible'); - fireEvent(document, new Event('visibilitychange')); - } else fireEvent(window, new Event('pageshow')); - }); - if (timing === 'held') { - await waitFor(() => expect(release).toBeDefined()); - expect(router.state.revalidation).toBe('loading'); - expect(screen.queryByText('Private review inventory')).not.toBeInTheDocument(); - await act(async () => release!()); - } - await waitFor(() => expect(router.state.revalidation).toBe('idle')); - expect(loader).toHaveBeenCalledTimes(2); - if (outcome === 'logout') expect(router.state.loaderData['layouts/milo.layout']).toEqual({ user: null }); - else expect(router.state.errors).not.toBeNull(); - expect(screen.queryByText('Private review inventory')).not.toBeInTheDocument(); - fireEvent(window, new Event('focus')); - await act(async () => {}); - expect(screen.queryByText('Private review inventory')).not.toBeInTheDocument(); - expect(loader).toHaveBeenCalledTimes(2); - router.dispose(); -}); diff --git a/ui/provider/src/pages/inventory-create.test.tsx b/ui/provider/src/pages/inventory-create.test.tsx index ee242933..8b9051c4 100644 --- a/ui/provider/src/pages/inventory-create.test.tsx +++ b/ui/provider/src/pages/inventory-create.test.tsx @@ -99,7 +99,7 @@ it.each(['__proto__', 'constructor', 'manufacturer', 'inventory'])('rejects unsu expect(screen.getByRole('link', { name: 'Back to inventory' })).toHaveAttribute('href', '/plugins/metal/inventory?kind=Device'); }); -it.each(['principal', 'logout', 'hidden', 'pagehide'] as const)('retires private task drafts on %s without transferring late writes', async transition => { +it.each(['principal', 'logout'] as const)('retires private task drafts on %s without transferring late writes', async transition => { const view = host('/create/device'); await screen.findByLabelText('Display name'); fireEvent.change(screen.getByLabelText('Display name'), { target: { value: 'Private draft' } }); From be46b9c2cfaa000b28a8945f01d344357f092d7b Mon Sep 17 00:00:00 2001 From: Kevin Williams Date: Wed, 25 Nov 2026 00:29:39 +0000 Subject: [PATCH 2/6] feat(ui): staff-portal list style with a category switcher and Catalog tab List pages follow staff-portal's Customers list: one toolbar row on top of a compact sortable datum-ui data table with a rows-per-page footer. - A category switcher (datum-ui Popover of links grouped by Equipment, Locations and Installation plans) replaces the group and kind tab rows. Each category shows its count once access resolves; the count is a description, not part of the name. - Manufacturers and Device types move to a Catalog tab with a two-option toggle. Links are absolute, and a kind requested on the other page is redirected there. - The toolbar row: borderless search, one Filter popover (facility, model, Clear filters), icon Refresh, Create. - The table keeps the directory rows' columns, attention edges and reasons, set on each row by InventoryListTable. - Fix: the list toolbar and table shared a React key, which duplicated the toolbar on every list/record switch. Co-Authored-By: Claude Opus 5.5 --- docs/development/staff-inventory-ui.md | 113 +++++------ ui/provider/README.md | 23 ++- ui/provider/public/plugin-manifest.json | 10 +- ui/provider/scripts/screenshot-pages.ts | 1 + .../src/components/field-select.test.tsx | 6 +- .../src/components/fleet-page.test.tsx | 2 +- ui/provider/src/components/fleet-page.tsx | 1 + .../src/components/hardware-catalog.test.tsx | 4 +- .../inventory-default-layout.test.tsx | 18 +- .../inventory-directory-heading.tsx | 34 +++- .../components/inventory-directory.test.tsx | 33 ++-- .../src/components/inventory-groups.ts | 13 +- .../src/components/inventory-list-table.tsx | 113 +++++++++++ .../components/inventory-location.test.tsx | 3 +- .../inventory-navigation-safety.test.tsx | 5 +- .../src/components/inventory-navigation.tsx | 182 +++++++++++++----- .../src/components/inventory-page-title.tsx | 17 +- .../inventory-record-layout.test.tsx | 2 +- .../inventory-tab-navigation.test.tsx | 159 ++++++++------- .../src/components/physical-inventory.css | 80 ++++++++ .../components/physical-inventory.test.tsx | 45 +++-- .../src/components/physical-inventory.tsx | 75 ++++---- ui/provider/src/main.tsx | 2 + .../src/pages/device-inventory-list.tsx | 43 ++++- .../src/pages/device-inventory.test.tsx | 3 + ui/provider/src/pages/hardware-catalog.tsx | 6 + .../src/pages/inventory-create.test.tsx | 12 +- ui/provider/src/test/field-select.ts | 6 + ui/provider/src/test/inventory-category.ts | 28 +++ ui/provider/vite.config.ts | 1 + 30 files changed, 702 insertions(+), 338 deletions(-) create mode 100644 ui/provider/src/components/inventory-list-table.tsx create mode 100644 ui/provider/src/pages/hardware-catalog.tsx create mode 100644 ui/provider/src/test/inventory-category.ts diff --git a/docs/development/staff-inventory-ui.md b/docs/development/staff-inventory-ui.md index e20f5d2f..f5f29543 100644 --- a/docs/development/staff-inventory-ui.md +++ b/docs/development/staff-inventory-ui.md @@ -1,77 +1,52 @@ # Staff physical inventory UI -## Grouped inventory navigation (implemented) +## Inventory and Catalog navigation (implemented) -This follow-up starts from PR133's exact head -`15f99a3234019faac8dca53248216d7719b60f97`. PR133 merged into -`feat/manual-inventory-records` as `ce65b369ccf4a0d113cd23db7ab5052b089a5b87`; -this navigation change retains that required source head rather than incorporating -unrelated target-branch changes. It supersedes the flat nine-category navigation -described in the historical notes below, not inventory contracts or IAM. +List pages follow staff-portal's list style (its Customers page): one toolbar +row directly on top of a compact sortable table, then the "rows per page · +1–N of M" footer. This replaces the earlier two rows of group and kind tabs. -| Primary route tab | Secondary navigation | Meaning | +| Page | Navigation | Categories | | --- | --- | --- | -| Equipment | Devices, Cables, Power feeds | Physical assets and recorded connections/supplies | -| Locations | Operational sites, Facilities, Racks | Site operational membership is distinct from physical Facility premises and rack containment | -| Installation plans | None | The directory is **Installation plans**, named once in the breadcrumb: installation plans and the devices registered against them. Plans do not allocate capacity | -| Hardware catalog | Manufacturers, Device types | Reference descriptions/templates, not installed assets or available capacity | - -- Uses the installed Datum `Tabs`, `TabsList variant="line"`, and - `TabsLinkTrigger` with React Router links, matching the pinned Compute and - cloud-portal sources. No custom underline imitation, sidebar, or category menu. - Primary tabs remain mounted; secondary tabs depend only on the selected group, - never access results. A group with one kind (Installation plans) has no - second tab row. At phone width the group tabs show short labels (Plans, - Catalog, and Sites for Operational sites) so all four fit on one row; the - accessible name stays the full title. -- Kind tabs carry the directory's count ("Devices 18"). A filtered directory - shows "shown/total" on its own tab, and a denied collection reads "?". The - count is the tab's accessible description; its name stays the title. - `PhysicalInventory` reports counts through `InventoryCountsProvider` only - after the session boundary resolves, so the public shell, pending and - unavailable states render no number. -- Equipment / Devices is the default. Group links select the first kind unless - already in that group. `?kind=...` and record/namespace bookmarks and the - child create routes are the only inventory URLs. Directories have no - breadcrumb, visible title or description: the tabs say where the reader is, - and an `sr-only` `h1` names the page. Detail and task breadcrumbs - include group and category, for example Equipment / Devices / record name. - Protected names appear only after successful access checks, not from URL text. -- Search, filters, Refresh and Create are page controls, not navigation. They - share one toolbar row above the table: search, the facility and model - filters, **Clear filters** (only while a filter is set), an icon-only - Refresh named "Refresh inventory", then Create. - Same-category links retain `q`, `location`, and `model`; switching categories - starts an unfiltered directory, and browser Back/Forward restores prior URLs. - Clicking the already-current tab is a no-op, not an implicit refresh. -- Same-principal presentation navigation reuses authorized default-namespace - collection data, including changes to the three known client-side filters - and the detail pages' `tab`, `view`, `selectedKind` and `selected` parameters. - The narrow presentation allowlist does not include unknown query parameters, - route changes, form submissions, or explicit revalidation. Host loaders still - verify navigations. During a presentation navigation the page already on - screen stays (the location has not changed yet, so nothing new is shown) and - writes are withheld until the host check finishes; other navigations show the - pending shell. Changed principal, logout, real denial, hidden/pagehide, and - unknown-scope boundaries still fence/clear private data. Operation - generations restart independently of retained read caches. -- Route tabs use manual activation: arrows/Home/End move focus, Enter or Space - activates the focused link. Lists are named and selected tabs expose their - selected/current state, with visible keyboard focus. No dangling panel IDs are - emitted for route-linked tabs. Dirty dialog/task navigation, immutable edit - baselines, unknown write outcomes, and visible blur/focus no-op behavior remain. - -Synthetic validation covers direct links for all nine kinds, group defaults, -detail/task breadcrumbs, dirty task navigation, keyboard focus/activation, -Back/Forward and filters, stable access-state navigation, and zero additional -collection reads for same-principal presentation changes. Provider and consumer -full tests, typechecks, and production builds pass. Local Chromium fixture checks -at 1280px and 390px verify actual underline components, mobile scroll containment, -group and secondary routes, rack breadcrumbs, and Arrow/End/Enter/Space navigation -without page errors. The 390px page stays 390px wide while the primary tab row -scrolls internally. These are not authenticated staff-portal or staging acceptance. -No live writes, deployment, schema changes, or new capacity-allocation semantics -are introduced; Go validation is not rerun because this follow-up changes no Go. +| Inventory | A category switcher (like staff-portal's `SectionSwitcher`): a datum-ui Popover of links grouped by Equipment, Locations and Installation plans | Devices, Cables, Power feeds · Operational sites, Facilities, Racks · Installation plans | +| Catalog (its own Bare Metal tab) | A two-option pill toggle (like staff-portal's `ViewTabs`) | Manufacturers, Device types | + +Manufacturers and Device types are reference descriptions and templates, not +installed equipment or capacity, so they live on the Catalog page. A record +link always reaches the page its kind lives on: links are absolute, and a kind +requested on the other page is redirected there, which keeps old bookmarks and +relative links working. + +- The navigation renders outside the session boundary and is laid over the left + end of the toolbar row by the page frame (`.inventory-list-frame`); the row + reserves its measured width (`--inventory-switcher-w`). On detail pages + (`.inventory-detail-frame`) it is hidden but stays mounted. At phone width it + sits above the row and the Filter button shows only its icon. +- Each category carries its count ("Devices 18"): the switcher trigger shows the + current one, and the menu and Catalog toggle show every one. A filtered + directory shows "shown/total" and a denied collection "?". The count is the + link's accessible description, never part of its name. `PhysicalInventory` + reports counts through `InventoryCountsProvider` only after the session + boundary resolves, so the public shell and pending and unavailable states + render no number. +- The switcher opens on the current category; arrow keys move between + categories. Choosing the current category is not a navigation. Devices is the + Inventory default and Manufacturers the Catalog default. Directories have no + breadcrumb, visible title or description; an `sr-only` `h1` names the page. +- The toolbar row: a borderless search (applies as the reader types; Enter + applies at once), one **Filter** popover for facility and model with + **Clear filters**, an icon-only Refresh named "Refresh inventory", then + Create. Same-category links retain `q`, `location` and `model`; switching + categories starts an unfiltered directory; Back and Forward restore prior URLs. +- The table is datum-ui's `DataTable.Client` at compact density: sortable + uppercase headers, one-line cells, the whole row opens the record. Columns + come from `inventory-directory-rows.ts` per record type. A row that needs a + second look keeps its coloured edge (red for a conflict, amber for + unavailable data) and its reasons as the row tooltip (`data-attention` and + `title`, set on each row by `InventoryListTable`). +- Same-principal presentation navigation reuses loaded collections and keeps the + page on screen while the host loads; see + [Session boundary](#session-boundary-a-change-of-signed-in-user-implemented). ## Page design rules diff --git a/ui/provider/README.md b/ui/provider/README.md index 935b49c3..68716876 100644 --- a/ui/provider/README.md +++ b/ui/provider/README.md @@ -208,18 +208,17 @@ to that array instead. ## Differences from the consumer plugin -Inventory uses four route-linked Datum underline groups: Equipment (Devices, -Cables, Power feeds), Locations (Operational sites, Facilities, Racks), Installation -plans, and Hardware catalog (Manufacturers, Device types). Only the selected -group's secondary navigation is shown. Installation plans opens the existing -Claims & registrations directory; plans do not allocate capacity. Site membership and -Facility premises remain distinct. The default is Equipment / Devices. -Search/filter/refresh/Create stay in the page toolbar. Existing query bookmarks, -detail and task routes work with group/category breadcrumbs; Back/Forward restores -filters. Static navigation survives access checks and denial without exposing -protected names or counts. Rows scroll horizontally on small screens, with -keyboard-focus navigation and Enter/Space link activation. See the -[implemented navigation and safety boundaries](../../docs/development/staff-inventory-ui.md#grouped-inventory-navigation-implemented). +Inventory and Catalog list pages follow staff-portal's list style: one toolbar +row (a category switcher grouped by Equipment, Locations and Installation plans, +or on Catalog a Manufacturers / Device types toggle; then search, Filter, +Refresh and Create) on top of a compact sortable datum-ui data table with a +rows-per-page footer. Each category shows its count once access resolves. +Installation plans do not allocate capacity, and Site membership and Facility +premises remain distinct. Devices is the Inventory default. Existing query +bookmarks and detail and task routes keep working, including old Manufacturer +and Device type links, which redirect to Catalog; Back and Forward restore +filters. See the +[implemented navigation](../../docs/development/staff-inventory-ui.md#inventory-and-catalog-navigation-implemented). The Inventory tab loads all six physical inventory collections with API pagination. Counts describe loaded records, not capacity or verified equipment. Unknown diff --git a/ui/provider/public/plugin-manifest.json b/ui/provider/public/plugin-manifest.json index 79bd060a..91a279b6 100644 --- a/ui/provider/public/plugin-manifest.json +++ b/ui/provider/public/plugin-manifest.json @@ -8,7 +8,8 @@ "MachineProfileList": "./src/pages/machine-profile-list.tsx", "MachineClassList": "./src/pages/machine-class-list.tsx", "DeviceInventoryList": "./src/pages/device-inventory-list.tsx", - "InventoryCreatePage": "./src/pages/inventory-create.tsx" + "InventoryCreatePage": "./src/pages/inventory-create.tsx", + "HardwareCatalog": "./src/pages/hardware-catalog.tsx" }, "extensions": [ { @@ -54,6 +55,13 @@ "path": "inventory/create/:kind", "component": { "$codeRef": "InventoryCreatePage" } } + }, + { + "type": "portal.page/platform", + "properties": { + "path": "catalog", + "component": { "$codeRef": "HardwareCatalog" } + } } ] } diff --git a/ui/provider/scripts/screenshot-pages.ts b/ui/provider/scripts/screenshot-pages.ts index 874b8cf3..3d40ebfe 100644 --- a/ui/provider/scripts/screenshot-pages.ts +++ b/ui/provider/scripts/screenshot-pages.ts @@ -51,6 +51,7 @@ const record = (kind: string, name: string, extra = '') => `${INVENTORY}?kind=${ export const PAGES: CapturePage[] = [ { name: 'inventory-list', path: INVENTORY, ready: '[data-testid="fleet-plugin-inventory-list"] table' }, + { name: 'catalog-list', path: '/plugins/metal-datumapis-com/catalog', ready: '[data-testid="fleet-plugin-catalog"] table' }, { name: 'capacity-list', path: '/plugins/metal-datumapis-com', ready: '[data-testid="fleet-plugin-capacity-table"] table' }, { name: 'capacity-pool', path: '/plugins/metal-datumapis-com?namespace=fleet-provider&pool=central-metal', ready: '[data-testid="fleet-plugin-capacity-filter"]', viewports: ['desktop-light'] }, { name: 'profile-list', path: '/plugins/metal-datumapis-com/profiles', ready: '[data-testid="fleet-plugin-profile-table"] table' }, diff --git a/ui/provider/src/components/field-select.test.tsx b/ui/provider/src/components/field-select.test.tsx index c3a2e81f..6077d0c1 100644 --- a/ui/provider/src/components/field-select.test.tsx +++ b/ui/provider/src/components/field-select.test.tsx @@ -3,7 +3,7 @@ import { Label } from '@datum-cloud/datum-ui/label'; import { useState } from 'react'; import { MemoryRouter } from 'react-router'; import { expect, it, vi } from 'vitest'; -import { chooseValue, openSelect, selectedValue, selectOptions } from '../test/field-select'; +import { chooseValue, openSelect, selectedValue, selectOptions, openFilters } from '../test/field-select'; import { FieldSelect } from './field-select'; import { InventoryForm } from './inventory-form-surface'; import { InventoryToolbar } from './inventory-directory-heading'; @@ -15,6 +15,7 @@ it('filters the directory from the keyboard and clears with the All choice', () const onLocation = vi.fn(); const onModel = vi.fn(); render(); + openFilters(); const facility = screen.getByRole('combobox', { name: 'Filter by facility' }); expect(facility).toHaveTextContent('Site A'); expect(selectOptions(facility).map(option => option.text)).toEqual(['All facilities', 'Site A', 'Site B']); @@ -31,7 +32,8 @@ it('filters the directory from the keyboard and clears with the All choice', () it('disables a filter that has no handler', () => { render(); - expect(screen.getByRole('combobox', { name: 'Filter by facility' })).toBeDisabled(); + // With no filter handlers the Filter button itself is disabled. + expect(screen.getByRole('button', { name: 'Filter' })).toBeDisabled(); }); function RequiredPlan({ onSubmit }: { onSubmit: () => void }) { diff --git a/ui/provider/src/components/fleet-page.test.tsx b/ui/provider/src/components/fleet-page.test.tsx index 3be13426..dcedfb62 100644 --- a/ui/provider/src/components/fleet-page.test.tsx +++ b/ui/provider/src/components/fleet-page.test.tsx @@ -27,6 +27,6 @@ it('shows cached counts on Inventory without reading any Bare Metal list', () => it('renders the tabs without counts outside a QueryClient', () => { renderInventory(); - expect(screen.getAllByRole('tab').map((tab) => tab.textContent)).toEqual(['Capacity', 'Profiles', 'Classes', 'Inventory']); + expect(screen.getAllByRole('tab').map((tab) => tab.textContent)).toEqual(['Capacity', 'Profiles', 'Classes', 'Inventory', 'Catalog']); expect(fetcher).not.toHaveBeenCalled(); }); diff --git a/ui/provider/src/components/fleet-page.tsx b/ui/provider/src/components/fleet-page.tsx index 515d1298..8fd1a4d7 100644 --- a/ui/provider/src/components/fleet-page.tsx +++ b/ui/provider/src/components/fleet-page.tsx @@ -81,6 +81,7 @@ export function FleetPage({ { label: 'Profiles', href: `${base}/profiles` }, { label: 'Classes', href: `${base}/classes` }, { label: 'Inventory', href: `${base}/inventory` }, + { label: 'Catalog', href: `${base}/catalog` }, ]; const active = tabs.slice(1).find((t) => pathname.startsWith(t.href))?.href ?? base; diff --git a/ui/provider/src/components/hardware-catalog.test.tsx b/ui/provider/src/components/hardware-catalog.test.tsx index 3c00db61..6b8f08f1 100644 --- a/ui/provider/src/components/hardware-catalog.test.tsx +++ b/ui/provider/src/components/hardware-catalog.test.tsx @@ -1,6 +1,6 @@ import { chooseValue, selectOptions, setField } from '../test/field-select'; import { findEnabledButton } from '../test/enabled-button'; -import { fireEvent, render, screen } from '@testing-library/react'; +import { fireEvent, render, screen, within } from '@testing-library/react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { MemoryRouter } from 'react-router'; import { afterEach, describe, expect, it, vi } from 'vitest'; @@ -131,7 +131,7 @@ describe('hardware catalog readers', () => { fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'private old vendor' } }); fireEvent.submit(screen.getByRole('search')); expect(screen.getByRole('link', { name: 'Private vendor label' })).toBeInTheDocument(); - fireEvent.click(screen.getByRole('tab', { name: 'Device types' })); + fireEvent.click(within(screen.getByRole('navigation', { name: 'Catalog categories' })).getByRole('link', { name: 'Device types' })); fireEvent.click(screen.getByRole('link', { name: model.spec.displayName })); expect(screen.getByText(/Template-only port/)).toBeInTheDocument(); // The template is listed in the model's component table, as catalog only, not as an installed component. diff --git a/ui/provider/src/components/inventory-default-layout.test.tsx b/ui/provider/src/components/inventory-default-layout.test.tsx index 3bce7a32..2f6cd8f5 100644 --- a/ui/provider/src/components/inventory-default-layout.test.tsx +++ b/ui/provider/src/components/inventory-default-layout.test.tsx @@ -4,7 +4,8 @@ import { MemoryRouter } from 'react-router'; import { beforeEach, expect, it, vi } from 'vitest'; import { PhysicalInventory } from './physical-inventory'; import { InventoryNavigation, sections } from './inventory-navigation'; -import { inventoryGroup } from './inventory-groups'; +import { isCatalogKind } from './inventory-groups'; +import { chooseCategory } from '../test/inventory-category'; import { InventoryPendingShell } from './inventory-directory-heading'; import { toInventory, type Inventory } from '../inventory'; import { fixturePhysicalClaims, fixturePhysicalDevices, fixturePhysicalRecords } from '../lib/fixtures'; @@ -29,21 +30,23 @@ function shape(container: HTMLElement) { it.each(sections)('keeps $kind category, heading, action and filter structure across pending/allowed/denied', section => { const client = new QueryClient(); - const view = (data?: Inventory) => {data ? :

Checking inventory access…

}
; + const catalogKind = isCatalogKind(section.kind); + const view = (data?: Inventory) => {data ? :

Checking inventory access…

}
; const result = render(view()); - const nav = screen.getByRole('navigation', { name: 'Inventory categories' }); + const navName = catalogKind ? 'Catalog categories' : 'Inventory categories'; + const nav = screen.getByRole('navigation', { name: navName }); const navMarkup = nav.innerHTML; const pendingShape = shape(result.container); const toolbarLabels = [...result.container.querySelectorAll('.inventory-toolbar [aria-label]')].map(element => element.getAttribute('aria-label')); - const group = inventoryGroup(section.kind); - expect(within(nav).getAllByRole('tab')).toHaveLength(4 + (group.kinds.length > 1 ? group.kinds.length : 0)); + if (catalogKind) expect(within(nav).getByRole('link', { name: section.title })).toHaveAttribute('aria-current', 'page'); + else expect(within(nav).getByRole('button', { name: `Inventory category: ${section.title}` })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: section.title })).toBeInTheDocument(); expect(screen.getByRole('searchbox')).toBeDisabled(); expect(result.container.textContent).not.toMatch(/Private vendor|Private model|Example compute server|\d+ of \d+ records/); result.rerender(view(inventory)); expect(shape(result.container)).toEqual(pendingShape); expect(screen.getByRole('searchbox')).toBeEnabled(); - expect(screen.getByRole('navigation', { name: 'Inventory categories' })).toBe(nav); + expect(screen.getByRole('navigation', { name: navName })).toBe(nav); expect(nav.innerHTML).toBe(navMarkup); result.rerender(view({ ...inventory, issues: { [section.kind]: { status: 403 } } })); expect(shape(result.container)).toEqual(pendingShape); @@ -89,7 +92,8 @@ it.each(sections)('rejects a forced foreign $kind detail even when a same-named expect(screen.getByText(/only supports the default namespace/)).toBeInTheDocument(); expect(screen.queryByText('Foreign private record')).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: /Edit display name|Correct location/ })).not.toBeInTheDocument(); - fireEvent.click(within(screen.getByRole('navigation', { name: 'Inventory categories' })).getByRole('tab', { name: section.kind === 'DeviceClaim' ? 'Installation plans' : section.title })); + if (isCatalogKind(section.kind)) fireEvent.click(within(screen.getByRole('navigation', { name: 'Catalog categories' })).getByRole('link', { name: section.title })); + else chooseCategory(section.title); expect(screen.queryByText('Foreign private record')).not.toBeInTheDocument(); expect(screen.queryByRole('columnheader', { name: 'Namespace' })).not.toBeInTheDocument(); }); diff --git a/ui/provider/src/components/inventory-directory-heading.tsx b/ui/provider/src/components/inventory-directory-heading.tsx index a21e6a7b..bb6bf0cb 100644 --- a/ui/provider/src/components/inventory-directory-heading.tsx +++ b/ui/provider/src/components/inventory-directory-heading.tsx @@ -1,7 +1,8 @@ import { Button } from '@datum-cloud/datum-ui/button'; import { Input } from '@datum-cloud/datum-ui/input'; import { Label } from '@datum-cloud/datum-ui/label'; -import { RefreshCw, Search } from 'lucide-react'; +import { Popover, PopoverContent, PopoverTrigger } from '@datum-cloud/datum-ui/popover'; +import { Plus, RefreshCw, Search, SlidersHorizontal } from 'lucide-react'; import { useEffect, useRef, useState, type ReactNode } from 'react'; import { useSearchParams } from 'react-router'; import { FieldSelect } from './field-select'; @@ -18,16 +19,16 @@ export function InventoryDirectoryHeading({ section }: { section: Section }) { return

{section.title}

; } -export function InventoryPendingShell({ children }: { children: ReactNode }) { +export function InventoryPendingShell({ children, scope = 'inventory' }: { children: ReactNode; scope?: 'inventory' | 'catalog' }) { const [params] = useSearchParams(); - const section = sections.find(item => item.kind === params.get('kind')) ?? sections[0]; + const section = sections.find(item => item.kind === params.get('kind')) ?? sections.find(item => item.kind === (scope === 'catalog' ? 'Manufacturer' : 'Device'))!; return
{children}
; } /** The disabled Create button that holds the slot until management access resolves. */ function CreatePlaceholder({ section }: { section: Section }) { if (!['Facility', 'Rack', 'Device', 'Cable', 'DeviceClaim'].includes(section.kind)) return null; - return <>

; + return <>

; } /** The search box applies as the reader types; the URL keeps the applied value. */ @@ -48,7 +49,11 @@ function SearchField({ section, search, onSearch }: { section: Section; search: ; } -/** One row above the table: search, filters, Clear filters when one is set, Refresh, then Create. */ +/** + * The list toolbar in staff-portal's list style: one row with the category + * switcher laid over its left end (by the page frame), a borderless search, + * one Filter popover for facility and model, then Refresh and Create. + */ export function InventoryToolbar({ section, search = '', onSearch, location = '', onLocation, facilities = [], model = '', onModel, models = [], onClear, onRetry, management }: { section: Section; search?: string; onSearch?: (value: string) => void; location?: string; onLocation?: (value: string) => void; facilities?: { value: string; label: string }[]; @@ -57,13 +62,24 @@ export function InventoryToolbar({ section, search = '', onSearch, location = '' }) { const hasLocation = ['Device', 'DeviceClaim', 'Rack', 'PowerFeed'].includes(section.kind); const hasModel = ['Device', 'Cable'].includes(section.kind); + const modelWord = section.kind === 'Cable' ? 'medium' : 'model'; + const active = [hasLocation && location, hasModel && model].filter(Boolean).length; return

- {hasLocation && onLocation?.(value)} none="All facilities" options={facilities} />} - {hasModel && onModel?.(value)} none={section.kind === 'Cable' ? 'All media' : 'All models'} options={models.map(value => ({ value, label: value }))} />} - {(location || model) && onClear && } + {(hasLocation || hasModel) && + + + + + {hasLocation && } + {hasModel && } + + + }
- +
; diff --git a/ui/provider/src/components/inventory-directory.test.tsx b/ui/provider/src/components/inventory-directory.test.tsx index c43d8fa4..d4fbf738 100644 --- a/ui/provider/src/components/inventory-directory.test.tsx +++ b/ui/provider/src/components/inventory-directory.test.tsx @@ -5,6 +5,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { PhysicalInventory } from './physical-inventory'; import { fixtureInventory } from '../lib/inventory-fixtures'; import type { Inventory } from '../inventory'; +import { categoryMenu, categoryTrigger } from '../test/inventory-category'; afterEach(() => vi.unstubAllGlobals()); @@ -18,39 +19,39 @@ const row = (name: string) => screen.getByRole('link', { name }).closest('tr')!; const cell = (rowName: string, column: string, tableName: string) => within(row(rowName)).getAllByRole('cell')[heads(tableName).indexOf(column)]; describe('directory header', () => { - it('has no breadcrumb, visible title, description or count strip; the tabs carry the place and the count', () => { + it('has no breadcrumb, visible title, description or count strip; the category switcher carries the place and the count', () => { const { container } = show('?kind=Device'); expect(screen.queryByRole('navigation', { name: /breadcrumb/i })).not.toBeInTheDocument(); expect(screen.getByRole('heading', { level: 1, name: 'Devices' })).toHaveClass('sr-only'); expect(container.querySelector('.inventory-page-title, .inventory-group-description, .inventory-record-count')).toBeNull(); expect(screen.queryByText(/ of \d+ records/)).not.toBeInTheDocument(); expect(screen.queryByText(/Physical hardware, identity/)).not.toBeInTheDocument(); - const devices = screen.getByRole('tab', { name: 'Devices' }); - expect(devices).toHaveAccessibleDescription(`${within(table('Devices')).getAllByRole('row').length - 1} records`); + const trigger = categoryTrigger(); + expect(trigger).toHaveAccessibleName('Inventory category: Devices'); + expect(trigger).toHaveAccessibleDescription(`${within(table('Devices')).getAllByRole('row').length - 1} records`); }); - it('reads "?" on the tab of a denied collection, never 0', () => { + it('reads "?" on the category of a denied collection, never 0', () => { show('?kind=Device', { ...fixtureInventory(), issues: { Cable: { status: 403 } } }); - const cables = screen.getByRole('tab', { name: 'Cables' }); + const cables = within(categoryMenu()).getByRole('link', { name: 'Cables' }); expect(cables.querySelector('.inventory-tab-count')).toHaveTextContent('?'); expect(cables).toHaveAccessibleDescription('Count unknown: this collection is unavailable'); }); - it('names the plans section "Installation plans" everywhere, with no empty second tab row', () => { + it('names the plans section "Installation plans" everywhere, with no tab rows', () => { const { container } = show('?kind=DeviceClaim'); - expect(screen.getByRole('tab', { name: 'Installation plans' })).toHaveAttribute('aria-selected', 'true'); + expect(categoryTrigger()).toHaveAccessibleName('Inventory category: Installation plans'); expect(screen.getByRole('heading', { level: 1, name: 'Installation plans' })).toBeInTheDocument(); expect(table('Installation plans')).toBeInTheDocument(); expect(container.textContent).not.toMatch(/Claims & registrations/); - expect(screen.getAllByRole('tablist')).toHaveLength(1); - expect(container.querySelector('.inventory-subcategories')).toBeNull(); + expect(screen.queryAllByRole('tablist')).toHaveLength(0); }); - it('keeps the full group name as the accessible name beside the phone label', () => { - show('?kind=Manufacturer'); - const catalog = screen.getByRole('tab', { name: 'Hardware catalog' }); - expect(catalog.querySelector('.inventory-tab-short')).toHaveAttribute('aria-hidden', 'true'); - expect(catalog.querySelector('.inventory-tab-short')).toHaveTextContent('Catalog'); + it('keeps Manufacturers and Device types out of the inventory switcher; the Catalog page toggles them', () => { + show('?kind=Device'); + const menu = categoryMenu(); + expect(within(menu).queryByRole('link', { name: 'Manufacturers' })).toBeNull(); + expect(within(menu).queryByRole('link', { name: 'Device types' })).toBeNull(); }); }); @@ -91,7 +92,7 @@ describe('directory columns', () => { for (const [kind, [title, columns]] of Object.entries(expected)) { const view = show(`?kind=${kind}`); expect(heads(title)).toEqual(columns); - expect(table(title)).toHaveClass('inventory-dense-table'); + expect(table(title).closest('[data-testid="fleet-plugin-inventory-table"]')).not.toBeNull(); expect(table(title).querySelector('small')).toBeNull(); view.unmount(); } @@ -147,7 +148,7 @@ describe('directory columns', () => { show('?kind=Cable', fixtureInventory('devices-denied')); const end = cell('DAC a01-01 eth0', 'A end', 'Cables'); expect(end).toHaveTextContent(/^\? · eth0 · Device records unavailable$/); - expect(end).toHaveAttribute('title', 'Device records unavailable'); + expect(end.querySelector('[title]')).toHaveAttribute('title', 'Device records unavailable'); expect(row('DAC a01-01 eth0')).toHaveAttribute('data-attention', 'unavailable'); expect(screen.queryByText(/Related endpoint unavailable|Compute a01-01/)).not.toBeInTheDocument(); }); diff --git a/ui/provider/src/components/inventory-groups.ts b/ui/provider/src/components/inventory-groups.ts index 15c44f35..46cc4e57 100644 --- a/ui/provider/src/components/inventory-groups.ts +++ b/ui/provider/src/components/inventory-groups.ts @@ -1,11 +1,20 @@ -// `short` is the label at phone width, where the four full labels do not fit one row. +// Inventory categories, grouped in the category switcher. Manufacturers and +// Device types are reference data, not installed equipment, so they live on +// the separate Catalog page. export const inventoryGroups = [ { title: 'Equipment', short: 'Equipment', kinds: ['Device', 'Cable', 'PowerFeed'] }, { title: 'Locations', short: 'Locations', kinds: ['Site', 'Facility', 'Rack'] }, { title: 'Installation plans', short: 'Plans', kinds: ['DeviceClaim'] }, - { title: 'Hardware catalog', short: 'Catalog', kinds: ['Manufacturer', 'DeviceType'] }, ] as const; +export const CATALOG_KINDS = ['Manufacturer', 'DeviceType'] as const; +export const catalogGroup = { title: 'Hardware catalog', short: 'Catalog', kinds: CATALOG_KINDS } as const; + +export function isCatalogKind(kind: string | null | undefined): boolean { + return CATALOG_KINDS.some(item => item === kind); +} + export function inventoryGroup(kind: string) { + if (isCatalogKind(kind)) return catalogGroup; return inventoryGroups.find(group => group.kinds.some(item => item === kind)) ?? inventoryGroups[0]; } diff --git a/ui/provider/src/components/inventory-list-table.tsx b/ui/provider/src/components/inventory-list-table.tsx new file mode 100644 index 00000000..65dde1b2 --- /dev/null +++ b/ui/provider/src/components/inventory-list-table.tsx @@ -0,0 +1,113 @@ +import { Button } from '@datum-cloud/datum-ui/button'; +import { DataTable, DataTableColumnHeader, useDataTablePagination, useDataTableRows, type DataTableFeatures } from '@datum-cloud/datum-ui/data-table'; +import type { ColumnDef, Row, RowData } from '@tanstack/react-table'; +import { ChevronLeft, ChevronRight } from 'lucide-react'; +import { useEffect, useLayoutEffect, useMemo, useRef, type ReactNode, type RefObject } from 'react'; +import { FieldSelect } from './field-select'; +import './physical-inventory.css'; + +export type InventoryListColumn = { + id: string; + header: string; + cell: (row: T) => ReactNode; + /** Plain value the column sorts by. */ + sort: (row: T) => string | number; +}; + +const PAGE_SIZES = [20, 50, 100]; + +/** + * The inventory list in staff-portal's list style: a datum-ui DataTable at + * compact density (uppercase sortable headers, dense rows) and the host's + * "rows per page · 1–N of M" footer. Search and filters stay with the caller, + * which keeps them in the URL; this table only sorts, pages and renders the + * rows it is given. Callers key it by record type: DataTable.Client adopts new + * rows a render after new columns, so one instance must never switch types. + */ +export function InventoryListTable({ label, rows, total, columns, rowKey, onOpen, empty, resource, pagination = true, rowMeta }: { + label: string; + rows: T[]; + total: number; + columns: InventoryListColumn[]; + rowKey: (row: T) => string; + onOpen: (row: T) => void; + empty: ReactNode; + resource: string; + /** Embedded tables that always fit one page leave the footer out. */ + pagination?: boolean; + /** + * Per-row marks: `attention` gives the row a coloured edge (red for a + * conflict, amber for unavailable data) and `title` is its tooltip, set on + * the row element as `data-attention` and `title`. + */ + rowMeta?: (row: T) => { attention?: 'conflict' | 'unavailable'; title?: string }; +}) { + const definitions = useMemo[]>(() => columns.map(column => ({ + id: column.id, + accessorFn: (row: T) => column.sort(row), + sortingFn: (left: Row, right: Row) => { + const a = column.sort(left.original); + const b = column.sort(right.original); + return typeof a === 'number' && typeof b === 'number' ? a - b : String(a).localeCompare(String(b), undefined, { numeric: true, sensitivity: 'base' }); + }, + header: ({ column: state }) => , + cell: ({ row }) => column.cell(row.original), + })), [columns]); + const table = useRef(null); + return +
+ { if (!window.getSelection()?.toString()) onOpen(row as T); }} /> + +
+ {pagination && total > 0 && } +
; +} + +/** + * DataTable.Content takes no table label. This sits after it inside the table + * context, so it re-renders with the rows and its layout effect runs in the + * same commit that (re)renders the table. + */ +function TableName({ container, label, rowMeta }: { container: RefObject; label: string; rowMeta?: (row: T) => { attention?: string; title?: string } }) { + // DataTable.Content renders one per row of the current page, in order, + // and takes no per-row attributes, so the row marks are set on them here. + const { rows } = useDataTableRows(); + useLayoutEffect(() => { + const table = container.current?.querySelector('table'); + if (!table) return; + if (table.getAttribute('aria-label') !== label) table.setAttribute('aria-label', label); + if (!rowMeta) return; + const elements = [...table.querySelectorAll('tbody > tr')]; + if (elements.length !== rows.length) return; + elements.forEach((element, index) => { + const meta = rowMeta(rows[index].original); + if (meta.attention) element.setAttribute('data-attention', meta.attention); else element.removeAttribute('data-attention'); + if (meta.title) element.setAttribute('title', meta.title); else element.removeAttribute('title'); + }); + }); + return null; +} + +function InventoryPagination({ total, resource }: { total: number; resource: string }) { + const pagination = useDataTablePagination(); + const { canNextPage, canPrevPage, nextPage, prevPage, pageIndex, pageSize, setPageSize, totalRows } = pagination; + const pageCount = pagination.mode === 'client' ? pagination.pageCount : undefined; + const setPageIndex = pagination.mode === 'client' ? pagination.setPageIndex : undefined; + // A narrower search or filter can leave the current page past the end. + useEffect(() => { if (pageCount !== undefined && pageIndex > 0 && pageIndex >= pageCount) setPageIndex?.(Math.max(0, pageCount - 1)); }, [pageCount, pageIndex, setPageIndex]); + const start = totalRows === 0 ? 0 : pageIndex * pageSize + 1; + const end = Math.min((pageIndex + 1) * pageSize, totalRows); + return
+
+ setPageSize(Number(value))} options={PAGE_SIZES.map(size => ({ value: String(size), label: String(size) }))} /> + Rows per page +
+
+ {start}–{end} of {totalRows} {resource}{totalRows !== total ? ` · ${total} total` : ''} +
+
+
+
; +} diff --git a/ui/provider/src/components/inventory-location.test.tsx b/ui/provider/src/components/inventory-location.test.tsx index 52dbf177..743769bd 100644 --- a/ui/provider/src/components/inventory-location.test.tsx +++ b/ui/provider/src/components/inventory-location.test.tsx @@ -1,4 +1,4 @@ -import { chooseValue } from '../test/field-select'; +import { chooseValue, openFilters } from '../test/field-select'; import { fireEvent, render, screen, within } from '@testing-library/react'; import { expect, it } from 'vitest'; import { MemoryRouter } from 'react-router'; @@ -123,6 +123,7 @@ it('does not invent rack units when the rack height is unknown', () => { }); it('filters by recorded model and facility without manufacturing a hardware type', () => { render(); + openFilters(); chooseValue(screen.getByRole('combobox', { name: 'Filter by model' }), 'Example 1U'); expect(screen.queryByRole('link', { name: 'orphan-synthetic-0009' })).not.toBeInTheDocument(); chooseValue(screen.getByRole('combobox', { name: 'Filter by facility' }), 'default/example-facility'); diff --git a/ui/provider/src/components/inventory-navigation-safety.test.tsx b/ui/provider/src/components/inventory-navigation-safety.test.tsx index e197e409..3bcbc0db 100644 --- a/ui/provider/src/components/inventory-navigation-safety.test.tsx +++ b/ui/provider/src/components/inventory-navigation-safety.test.tsx @@ -1,4 +1,5 @@ import { findEnabledButton } from '../test/enabled-button'; +import { chooseCategory } from '../test/inventory-category'; import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { createMemoryRouter, Outlet, RouterProvider } from 'react-router'; @@ -24,8 +25,8 @@ it('real directory category Link followed by fresh create remains usable', async })); const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: () => ({ user: { metadata: { uid: 'staff-a' } } }), element: , children: [{ path: 'inventory', element: }] }], { initialEntries: ['/inventory'] }); render(); - fireEvent.click(await screen.findByRole('tab', { name: 'Locations' })); - fireEvent.click(await screen.findByRole('tab', { name: 'Facilities' })); + await screen.findByRole('navigation', { name: 'Inventory categories' }); + chooseCategory('Facilities'); await open(false); fireEvent.click(screen.getByRole('button', { name: 'Create record' })); expect(await screen.findByRole('status')).not.toHaveTextContent('No write was dispatched'); diff --git a/ui/provider/src/components/inventory-navigation.tsx b/ui/provider/src/components/inventory-navigation.tsx index eccb7f3e..d9dfc3e2 100644 --- a/ui/provider/src/components/inventory-navigation.tsx +++ b/ui/provider/src/components/inventory-navigation.tsx @@ -1,22 +1,23 @@ import { Link, useLocation, useSearchParams } from 'react-router'; -import { Tabs, TabsLinkTrigger, TabsList } from '@datum-cloud/datum-ui/tabs'; -import { Building2, Cable, ClipboardList, HardDrive, Server, Zap } from 'lucide-react'; +import { Button } from '@datum-cloud/datum-ui/button'; +import { Popover, PopoverContent, PopoverTrigger } from '@datum-cloud/datum-ui/popover'; +import { Box, Building2, Cable, Check, ChevronDown, ClipboardList, Factory, HardDrive, MapPin, Server, Zap } from 'lucide-react'; import { inventoryDirectoryPath, inventoryReturnSearch } from './inventory-page-title'; -import { inventoryGroup, inventoryGroups } from './inventory-groups'; -import { createContext, useContext, useEffect, useId, useMemo, useState, type MouseEvent, type ReactNode } from 'react'; +import { CATALOG_KINDS, inventoryGroups, isCatalogKind } from './inventory-groups'; +import { createContext, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent, type ReactNode, type RefObject } from 'react'; import './physical-inventory.css'; // `short` is the tab label at phone width, where it differs. export const sections = [ { kind: 'Device', title: 'Devices', icon: HardDrive }, - { kind: 'Site', title: 'Operational sites', short: 'Sites', icon: Building2 }, + { kind: 'Site', title: 'Operational sites', short: 'Sites', icon: MapPin }, { kind: 'Facility', title: 'Facilities', icon: Building2 }, { kind: 'Rack', title: 'Racks', icon: Server }, { kind: 'DeviceClaim', title: 'Installation plans', icon: ClipboardList }, { kind: 'Cable', title: 'Cables', icon: Cable }, { kind: 'PowerFeed', title: 'Power feeds', icon: Zap }, - { kind: 'Manufacturer', title: 'Manufacturers', icon: Building2 }, - { kind: 'DeviceType', title: 'Device types', icon: Server }, + { kind: 'Manufacturer', title: 'Manufacturers', icon: Factory }, + { kind: 'DeviceType', title: 'Device types', icon: Box }, ] as const; /** @@ -45,57 +46,142 @@ export function useReportInventoryCounts(counts: InventoryCounts) { }, [key, report]); } -/** The count beside a kind tab. The tab's name stays its title; the count is its description. */ -function TabCount({ id, count }: { id: string; count?: { total?: number; shown?: number } }) { - if (!count) return null; +function countWords(count: { total?: number; shown?: number }) { const filtered = count.total !== undefined && count.shown !== undefined && count.shown !== count.total; const text = count.total === undefined ? '?' : filtered ? `${count.shown}/${count.total}` : String(count.total); const words = count.total === undefined ? 'Count unknown: this collection is unavailable' : filtered ? `${count.shown} of ${count.total} records` : `${count.total} ${count.total === 1 ? 'record' : 'records'}`; - return <>{words}; + return { text, words }; } -function TabLabel({ title, short }: { title: string; short?: string }) { - return short && short !== title ? <>{title} : <>{title}; +/** The visible count beside a category; its words are the category's description (CountWords), not part of its name. */ +function CountMark({ count }: { count?: { total?: number; shown?: number } }) { + if (!count) return null; + const { text, words } = countWords(count); + return ; } -export function InventoryNavigation({ kind, counts: given }: { kind?: string; counts?: InventoryCounts }) { - const [params] = useSearchParams(); +function CountWords({ id, count }: { id: string; count?: { total?: number; shown?: number } }) { + if (!count) return null; + return {countWords(count).words}; +} + +/** Publishes the navigation's width to the list frame so the toolbar row can reserve it. */ +function useFrameWidth(nav: RefObject) { + useLayoutEffect(() => { + const element = nav.current; + const frame = element?.closest('.inventory-list-frame'); + if (!element || !frame) return; + const publish = () => frame.style.setProperty('--inventory-switcher-w', `${element.offsetWidth}px`); + publish(); + if (typeof ResizeObserver === 'undefined') return; + const observer = new ResizeObserver(publish); + observer.observe(element); + return () => observer.disconnect(); + }); +} + +/** + * Inventory and Catalog navigation in staff-portal's list style. + * + * Inventory: one category switcher (like staff-portal's SectionSwitcher, a + * datum-ui Popover of plain links grouped by Equipment, Locations and + * Installation plans), each category with its record count. Catalog: its two + * categories as a pill toggle (like staff-portal's ViewTabs). The nav renders + * outside the session boundary; counts appear only once PhysicalInventory has + * reported them from inside it. On list pages the page frame + * (`.inventory-list-frame`) lays the nav over the left end of the toolbar row, + * which reserves `--inventory-switcher-w` for it. + */ +export function InventoryNavigation({ kind, counts: given, scope = 'inventory' }: { kind?: string; counts?: InventoryCounts; scope?: 'inventory' | 'catalog' }) { const reported = useContext(InventoryCountsContext).counts; const counts = given ?? reported; + return scope === 'catalog' ? : ; +} + +function useCategoryHref(activeKind: string) { const { pathname, search } = useLocation(); - const active = sections.find(item => item.kind === (kind ?? params.get('kind'))) ?? sections[0]; - const group = inventoryGroup(active.kind); - const href = (next: string) => `${inventoryDirectoryPath(pathname)}${inventoryReturnSearch(next === active.kind ? search : '', next)}`; - const subcategories = sections.filter(item => group.kinds.some(kind => kind === item.kind)); - const stayOnCurrentPage = (event: MouseEvent, target: string) => { - if (!event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey && target === `${pathname}${search}`) event.preventDefault(); - }; + const href = (next: string) => `${inventoryDirectoryPath(pathname, next)}${inventoryReturnSearch(next === activeKind ? search : '', next)}`; + const current = `${pathname}${search}`; + return { href, current }; +} + +function CatalogNavigation({ counts }: { counts?: InventoryCounts }) { + const [params] = useSearchParams(); + const nav = useRef(null); + useFrameWidth(nav); + const countID = useId(); + const active = isCatalogKind(params.get('kind')) ? params.get('kind')! : CATALOG_KINDS[0]; + const { href, current } = useCategoryHref(active); + return ; +} + +function CategorySwitcher({ kind, counts }: { kind?: string; counts?: InventoryCounts }) { + const [params] = useSearchParams(); + const { pathname, search } = useLocation(); + const requested = kind ?? params.get('kind'); + const active = sections.find(item => item.kind === requested && !isCatalogKind(item.kind)) ?? sections[0]; + const { href, current } = useCategoryHref(active.kind); + const [open, setOpen] = useState(false); + const menu = useRef(null); + const menuLabel = useId(); const countID = useId(); - const trigger = (value: string, title: string, short: string | undefined, selected: boolean) => stayOnCurrentPage(event, href(value))} - aria-current={selected ? 'page' : undefined} aria-controls={undefined} - onKeyDown={event => { if (event.key === ' ') { event.preventDefault(); event.currentTarget.click(); } }}> - - ; - return