diff --git a/docs/development/staff-inventory-ui.md b/docs/development/staff-inventory-ui.md index 3c2e50f1..fc4f1d23 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 @@ -272,15 +247,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 +500,132 @@ 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/navigation/unmount boundaries, operations +held (not retired) while the host re-runs its loaders or confirms the user on a +tab return, 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. Nothing else discards loaded inventory or open forms, +and nothing is shown while the user is being confirmed. + +**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. +That masking and re-reading was removed. + +**Decision (2026-11-25): re-check the user when a tab returns.** Removing the +hidden/pagehide handling also removed the only re-check of the signed-in user +after a tab had been in the background or in the back-forward cache. If another +user signed in elsewhere meanwhile, the old user's inventory stayed on screen +and a save went out under the new session. The host does not cover this: + +- The principal reaches the plugin only through the `layouts/milo.layout` + loader data, read by `HostedInventory` (`useRouteLoaderData`) and the router + subscription in `SessionQueries`. That loader calls `requireStaffUser` + ([milo.layout.tsx L16-L18](https://github.com/datum-cloud/staff-portal/blob/ba00ea6322933632f87ca37a175a386163d1bf02/app/layouts/milo.layout.tsx#L16-L18)) and runs + only on navigations and explicit revalidations. +- Staff-portal has no `focus`, `visibilitychange` or `pageshow` handling under + `app/` (searched at staff-portal `ba00ea6`). Its only automatic + `revalidate()` is the colour-scheme client hint + ([client-hints.tsx L28-L29](https://github.com/datum-cloud/staff-portal/blob/ba00ea6322933632f87ca37a175a386163d1bf02/app/components/misc/client-hints.tsx#L28-L29)), + and the root loader opts out of ordinary revalidation + ([root.tsx L73-L85](https://github.com/datum-cloud/staff-portal/blob/ba00ea6322933632f87ca37a175a386163d1bf02/app/root.tsx#L73-L85)). +- The host's shared QueryClient + ([query.ts L41-L47](https://github.com/datum-cloud/staff-portal/blob/ba00ea6322933632f87ca37a175a386163d1bf02/app/modules/tanstack/query.ts#L41-L47)) keeps + TanStack's default refetch on window focus, but that refreshes host queries, + not the Milo loader, so it never delivers a new principal to the plugin. + +So `SessionQueries` re-checks the user itself (`useReturnCheck` in +`ui/provider/src/components/inventory-session-boundary.tsx`), invisibly: + +1. Hiding the tab or `pagehide` *holds* the session's reads and operations. + A hold is not a cancellation. Loaded data stays, and a read or save in flight + simply waits: a read waits to start or to deliver its result, and a save + waits before it dispatches its write (`InventoryOperation.settle()` runs + immediately before every `dispatch()`). +2. Showing the tab again, or a `pageshow` (always when `persisted`, i.e. a + back-forward-cache restore), calls the host's `router.revalidate()`, which + re-runs the Milo loader. +3. When the host loaders have settled: if they name the same user, the hold is + released and held reads and saves go on. If they name another user or no + user, report an error, or `revalidate()` rejects, the session's operations + are invalidated and its reads suspended. Held writes are never sent, and a + new principal remounts the private cache, as for any change of user. After a + failed check, a later successful check opens the session again for new work + only. + +No "Checking…" text, placeholder or re-render is shown for any of this, and a +same-user return makes no request except the host loader. + +What happens now: + +| Event | Inventory on screen | Private cache | Open forms and in-flight saves | +| --- | --- | --- | --- | +| Focus or blur | Unchanged | Kept | Unchanged | +| Tab hidden, then shown; `pagehide`, then `pageshow` (including a back-forward-cache restore); same user | Unchanged | Kept | Held while hidden and until the host confirms the user, then continue | +| Tab return or `pageshow` that finds another user, no user, or cannot confirm the user | Replaced (another user) or session expired / host error | Replaced or discarded | Ended; a held write is never sent | +| Host loader revalidation, same user (for example a theme change) | Unchanged | Kept | New reads and saves wait while the loaders run, then continue | +| 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. + +Limit: a write already dispatched before the tab was hidden is not recalled; its +result is reported as unknown if the user turns out to have changed. 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 +and re-checks management access with a SelfSubjectAccessReview. + +Tests (`ui/provider/src/components/`): + +- `inventory-return-check.test.tsx`: the real inventory page. A same-user return + shows nothing and requests nothing but the host loader, and a held create + resumes. Refresh during a check reads nothing until it resolves. A different + user on return removes the old records, and the held create is never sent. A + back-forward-cache `pageshow` re-checks, with or without a `pagehide` first. + A failed check sends nothing. +- `inventory-visible-focus-save.test.tsx`: create, display-name and placement + saves held at their permission review or baseline read across a tab return, + for the same and another user. +- `reviewer-exact-staging.test.tsx`: overlapping return checks stay held until + the newest loader finishes, and logout or host failure on return (immediate + and held) removes the private page and refuses held work. +- `adversarial-review.test.tsx`: a check answered after another `pagehide` + keeps work held until the next return. +- `inventory-session-boundary.test.tsx`: same-user revalidation, hidden and + `pagehide` keep data and authority. A failed check stays closed until a later + check succeeds. +- `inventory-navigation-safety.test.tsx`: a same-user host revalidation holds a + pending save, then lets it finish with one write. ### Regression evidence and acceptance limits +The evidence below predates the 2026-11-24 session-boundary change. Statements +about hidden/pagehide masking describe removed behaviour. The background-return +check was restored on 2026-11-25 without masking (see +[Session boundary](#session-boundary-a-change-of-signed-in-user-implemented)), +and its generation, after-pagehide, failed-check and logout/failure tests were +restored in that form. + 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 +683,9 @@ 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 should +do nothing. Pagehide/pageshow re-runs the host loader with no visible change. 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/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..181b606d 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' }, @@ -86,24 +87,24 @@ export const PAGES: CapturePage[] = [ // A Cable whose ends land on opposite rack faces carries a check note, shown in the port's card. { name: 'opposite-face-check', path: record('Device', 'example-app-a01'), ready: '.inventory-port-grid', click: tile('net0') }, // Detail and list pages for each kind, for page-design review. - { name: 'cable-detail', path: record('Cable', 'example-brk-swp49'), ready: '.inventory-page-title' }, + { name: 'cable-detail', path: record('Cable', 'example-brk-swp49'), ready: '.inventory-entity-header' }, // A one-lane Cable is one line; a duplicate's shared end is red. { name: 'cable-detail-dac', path: record('Cable', 'example-dac-a01-01-eth0'), ready: '.inventory-cable-line' }, { name: 'cable-detail-conflict', path: record('Cable', 'example-dac-a01-01-eth1-dup'), ready: '.inventory-cable-line' }, - { name: 'power-feed-detail', path: record('PowerFeed', 'example-feed-a'), ready: '.inventory-page-title' }, - { name: 'facility-detail', path: record('Facility', 'example-dc1'), ready: '.inventory-page-title' }, - { name: 'site-detail', path: record('Site', 'example-site-one'), ready: '.inventory-page-title' }, - { name: 'device-type-detail', path: record('DeviceType', 'example-server-1u'), ready: '.inventory-page-title' }, - { name: 'manufacturer-detail', path: record('Manufacturer', 'example-compute'), ready: '.inventory-page-title' }, + { name: 'power-feed-detail', path: record('PowerFeed', 'example-feed-a'), ready: '.inventory-entity-header' }, + { name: 'facility-detail', path: record('Facility', 'example-dc1'), ready: '.inventory-entity-header' }, + { name: 'site-detail', path: record('Site', 'example-site-one'), ready: '.inventory-entity-header' }, + { name: 'device-type-detail', path: record('DeviceType', 'example-server-1u'), ready: '.inventory-entity-header' }, + { name: 'manufacturer-detail', path: record('Manufacturer', 'example-compute'), ready: '.inventory-entity-header' }, { name: 'site-devices', path: record('Site', 'example-site-one', '&tab=devices'), ready: '[data-tab="devices"] table' }, { name: 'site-plans', path: record('Site', 'example-site-one', '&tab=plans'), ready: '[data-tab="plans"] table' }, { name: 'facility-unracked', path: record('Facility', 'example-dc1', '&tab=unracked'), ready: '[data-tab="unracked"] table' }, { name: 'facility-feeds', path: record('Facility', 'example-dc1', '&tab=feeds'), ready: '[data-tab="feeds"] table' }, { name: 'facility-cables', path: record('Facility', 'example-dc1', '&tab=cables'), ready: '[data-tab="cables"] table' }, { name: 'device-type-leaf', path: record('DeviceType', 'example-leaf-48x25-8x100'), ready: '.inventory-drawing' }, - { name: 'device-type-pdu', path: record('DeviceType', 'example-pdu-8'), ready: '.inventory-page-title' }, + { name: 'device-type-pdu', path: record('DeviceType', 'example-pdu-8'), ready: '.inventory-entity-header' }, { name: 'manufacturer-devices', path: record('Manufacturer', 'example-compute', '&tab=devices'), ready: '[data-tab="devices"] table' }, - { name: 'claim-detail', path: record('DeviceClaim', 'example-srv-a01-01-install'), ready: '.inventory-page-title' }, + { name: 'claim-detail', path: record('DeviceClaim', 'example-srv-a01-01-install'), ready: '.inventory-entity-header' }, { name: 'devices-list', path: `${INVENTORY}?kind=Device`, ready: '[data-testid="fleet-plugin-inventory-table"]' }, { name: 'cables-list', path: `${INVENTORY}?kind=Cable`, ready: '[data-testid="fleet-plugin-inventory-table"]' }, { name: 'racks-list', path: `${INVENTORY}?kind=Rack`, ready: '[data-testid="fleet-plugin-inventory-table"]' }, diff --git a/ui/provider/src/components/adversarial-review.test.tsx b/ui/provider/src/components/adversarial-review.test.tsx index bd83c7bf..18356b37 100644 --- a/ui/provider/src/components/adversarial-review.test.tsx +++ b/ui/provider/src/components/adversarial-review.test.tsx @@ -8,6 +8,8 @@ import { InventorySessionBoundary } from './inventory-session-boundary'; import DeviceInventoryList from '../pages/device-inventory-list'; import { inventoryPayload, INVENTORY_FIELD_MANAGER } from '../lib/inventory-management'; import { focusManager } from '@tanstack/react-query'; +import { useContext } from 'react'; +import { InventoryOperationContext, type InventoryOperationScope } from '../lib/inventory-operation'; const values = { name: 'review-facility', namespace: 'default', displayName: 'Original label', facility: '', height: '' }; const original = { ...inventoryPayload('Facility', values), metadata: { name: values.name, namespace: 'default', uid: 'synthetic-only', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; @@ -138,16 +140,33 @@ it('must not silently advance an open edit form to a refreshed resourceVersion', expect(patches).toEqual([]); }); -it('must keep inventory concealed if foreground verification finishes after another pagehide', async () => { +// Restored from "must keep inventory concealed if foreground verification +// finishes after another pagehide". The page is no longer concealed during a +// check; the risk it guarded is that a check answered for an earlier return +// lets work through after the page has gone away again. It must not. +it('must keep work held if a return check 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 }] }]); + let scope: InventoryOperationScope | undefined; + function Private() { scope = useContext(InventoryOperationContext); return

Private inventory label

; } + 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: }] }]); 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')); + const operation = scope!.begin(); + let settled = false; + void operation.settle().then(() => { settled = true; }); await act(async () => { release!(); }); - expect(screen.queryByText('Private inventory label')).not.toBeInTheDocument(); + await waitFor(() => expect(router.state.revalidation).toBe('idle')); + expect(scope!.held).toBe(true); + expect(settled).toBe(false); + // The next return checks again, and only then does the work go on. + fireEvent(window, new Event('pageshow')); + await waitFor(() => expect(settled).toBe(true)); + expect(count).toBe(3); + expect(screen.getByText('Private inventory label')).toBeInTheDocument(); + router.dispose(); }); diff --git a/ui/provider/src/components/connections-power-pages.test.tsx b/ui/provider/src/components/connections-power-pages.test.tsx index a2808f13..90c0b4e5 100644 --- a/ui/provider/src/components/connections-power-pages.test.tsx +++ b/ui/provider/src/components/connections-power-pages.test.tsx @@ -90,11 +90,12 @@ describe('Installation plan page', () => { expect(screen.queryByText('No cable references recorded.')).toBeNull(); }); - it('names the directory once in the breadcrumb, as Installation plans', () => { + it('names the directory once, in the back link, as Installation plans', () => { show(PLAN); - const crumbs = document.querySelector('nav[aria-label="breadcrumb"]')!; - expect(crumbs.textContent?.match(/Installation plans/g)).toHaveLength(1); - expect(crumbs).not.toHaveTextContent(/Claims & registrations/); + const back = document.querySelector('.inventory-back-link')!; + expect(back).toHaveTextContent(/^Installation plans$/); + expect(document.querySelector('nav[aria-label="breadcrumb"]')).toBeNull(); + expect(document.body).not.toHaveTextContent(/Claims & registrations/); }); it('links the expected hardware to its model, and marks a registered device reporting another model in red', () => { 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/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-location.tsx b/ui/provider/src/components/inventory-location.tsx index 4a77c448..640aecc6 100644 --- a/ui/provider/src/components/inventory-location.tsx +++ b/ui/provider/src/components/inventory-location.tsx @@ -96,7 +96,7 @@ export function RackOverview({ rack, inventory, selection, toolbar }: { rack: Ph return
; 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..0496db78 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'); @@ -49,7 +50,7 @@ it.each([false, true])('same-principal query navigation retains usable managemen expect(writes).toEqual([editing ? 'PATCH' : 'POST']); }); -it.each([false, true].flatMap(editing => ['navigation', 'revalidation'].map(transition => ({ editing, transition }))))('$transition revokes pending work while admitting a fresh form: edit=$editing', async ({ editing, transition }) => { +it.each([false, true])('navigation revokes pending work while admitting a fresh form: edit=%s', async editing => { let reviews = 0; let release: ((value: unknown) => void) | undefined; const writes: string[] = []; @@ -66,10 +67,7 @@ it.each([false, true].flatMap(editing => ['navigation', 'revalidation'].map(tran await open(editing); fireEvent.click(screen.getByRole('button', { name: editing ? 'Save changes' : 'Create record' })); await waitFor(() => expect(release).toBeDefined()); - await act(async () => { - if (transition === 'revalidation') await router.revalidate(); - else await router.navigate('/?kind=Facility&name=independent-review'); - }); + await act(async () => { await router.navigate('/?kind=Facility&name=independent-review'); }); await open(editing); await act(async () => release!(response({ status: { allowed: true } }))); expect(writes).toEqual([]); @@ -79,6 +77,43 @@ it.each([false, true].flatMap(editing => ['navigation', 'revalidation'].map(tran expect(writes).toEqual([editing ? 'PATCH' : 'POST']); }); +it.each([false, true])('a same-user host revalidation holds a pending save, then lets it finish: edit=%s', async editing => { + let reviews = 0; + let release: ((value: unknown) => void) | undefined; + let confirm: (() => void) | undefined; + 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); + })); + let held = false; + const loader = vi.fn(async () => { + if (held) await new Promise(resolve => { confirm = resolve; }); + return { user: { metadata: { uid: 'staff-a' } } }; + }); + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader, element: , children: [{ index: true, element: }] }]); + render(); + await open(editing); + fireEvent.click(screen.getByRole('button', { name: editing ? 'Save changes' : 'Create record' })); + await waitFor(() => expect(release).toBeDefined()); + held = true; + let revalidated: Promise | undefined; + act(() => { revalidated = router.revalidate(); }); + await waitFor(() => expect(confirm).toBeDefined()); + // The permission review answers while the host is still confirming the user: nothing is sent yet. + await act(async () => release!(response({ status: { allowed: true } }))); + expect(writes).toEqual([]); + expect(screen.getByRole('button', { name: 'Saving…' })).toBeInTheDocument(); + await act(async () => { confirm!(); await revalidated; }); + await screen.findByText(editing ? 'Display name saved.' : 'Facility created.'); + expect(screen.queryByText(/No write was dispatched/)).not.toBeInTheDocument(); + expect(writes).toEqual([editing ? 'PATCH' : 'POST']); +}); + async function open(editing: boolean) { const opener = await findEnabledButton({ name: editing ? 'Edit display name' : 'Create facility' }); fireEvent.click(opener); 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