Просмотр исходного кода

Open the status menu from the stage the work order is in (#663)

Bernt Christian Egeland 5 дней назад
Родитель
Сommit
1e7b44e82a

+ 4 - 2
e2e/specs/quotes/add-to-work-order.spec.ts

@@ -258,7 +258,7 @@ test.describe('a finished job is not offered', () => {
 
   /** The status stepper in the work order's header: one button per stage. */
   function stage(page: Page, name: string) {
-    return page.getByTestId('status-stepper').getByRole('button', { name: new RegExp(name) })
+    return page.getByTestId('status-stepper').getByLabel(new RegExp(name))
   }
 
   test.beforeAll(async () => {
@@ -286,7 +286,9 @@ test.describe('a finished job is not offered', () => {
     await page.goto(jobUrl)
     await settle(page)
     await expect(async () => {
-      await stage(page, 'Completed').click()
+      if ((await stage(page, 'Completed').getAttribute('aria-current')) !== 'step') {
+        await stage(page, 'Completed').click()
+      }
       await expect(stage(page, 'Completed')).toHaveAttribute('aria-current', 'step', {
         timeout: 2_000,
       })

+ 5 - 2
e2e/specs/vehicles/meters.spec.ts

@@ -209,13 +209,16 @@ test.describe('meters', () => {
 
 /** The status stepper in the page header: one button per stage. */
 function stage(page: Page, name: string) {
-  return page.getByTestId('status-stepper').getByRole('button', { name: new RegExp(name) })
+  return page.getByTestId('status-stepper').getByLabel(new RegExp(name))
 }
 
 /** Moves the job to a stage. A click before hydration does nothing, so it is repeated. */
 async function setStage(page: Page, name: string): Promise<void> {
   await expect(async () => {
-    await stage(page, name).click()
+    // Once there, a click would open the stage's menu, or do nothing.
+    if ((await stage(page, name).getAttribute('aria-current')) !== 'step') {
+      await stage(page, name).click()
+    }
     await expect(stage(page, name)).toHaveAttribute('aria-current', 'step', { timeout: 2_000 })
   }).toPass({ timeout: 30_000 })
 }

+ 5 - 2
e2e/specs/work-orders/lifecycle.spec.ts

@@ -39,13 +39,16 @@ let jobUrl = ''
 
 /** The status stepper in the page header: one button per stage. */
 function stage(page: Page, name: string): Locator {
-  return page.getByTestId('status-stepper').getByRole('button', { name: new RegExp(name) })
+  return page.getByTestId('status-stepper').getByLabel(new RegExp(name))
 }
 
 /** Moves the job to a stage. A click before hydration does nothing, so it is repeated. */
 async function setStatus(page: Page, name: string): Promise<void> {
   await expect(async () => {
-    await stage(page, name).click()
+    // Once there, a click would open the stage's menu, or do nothing.
+    if ((await stage(page, name).getAttribute('aria-current')) !== 'step') {
+      await stage(page, name).click()
+    }
     await expect(stage(page, name)).toHaveAttribute('aria-current', 'step', { timeout: 2_000 })
   }).toPass({ timeout: 30_000 })
 }

+ 4 - 3
e2e/specs/work-orders/modern-layout.spec.ts

@@ -153,11 +153,12 @@ test.describe('the work order page', () => {
     // Each control of the status stepper stays in its own space: a label is
     // cut short rather than running into the next. Three stages, and the
     // arrow beside "In Progress" that opens the statuses filed under it
-    // (always there, for "Waiting Parts"): four buttons in all on a workshop
-    // that has defined no statuses of its own.
+    // (always there, for "Waiting Parts"): four controls in all on a workshop
+    // that has defined no statuses of its own. The stage the job is in is not
+    // a button when it has no menu, so it is counted by being current.
     const stages = await page
       .getByTestId('status-stepper')
-      .getByRole('button')
+      .locator('button, [aria-current="step"]')
       .evaluateAll((buttons) => buttons.map((b) => b.getBoundingClientRect().toJSON()))
     expect(stages).toHaveLength(4)
     for (let i = 1; i < stages.length; i++) {

+ 1 - 1
e2e/specs/work-orders/modern-page.spec.ts

@@ -89,7 +89,7 @@ function stepper(page: Page): Locator {
 }
 
 async function expectStatus(page: Page, name: RegExp): Promise<void> {
-  await expect(stepper(page).getByRole('button', { name })).toHaveAttribute('aria-current', 'step')
+  await expect(stepper(page).getByLabel(name)).toHaveAttribute('aria-current', 'step')
 }
 
 test.describe('the overhauled work order page', () => {

+ 158 - 0
src/__tests__/features/vehicles/status-stepper.test.tsx

@@ -0,0 +1,158 @@
+/**
+ * The status stepper on the modern work order page. The stage the job is in
+ * opens its menu of statuses when it has one; without one it is not a
+ * control at all. The other stages move the job, as they always have.
+ */
+
+import { fireEvent, render, screen, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { describe, expect, it, vi } from 'vitest'
+import { StatusStepper } from '@/features/vehicles/Components/service-page/modern/StatusStepper'
+import type { WorkOrderStatusOption } from '@/features/work-order-statuses/Lib/stages'
+
+const noop = () => undefined
+vi.stubGlobal(
+  'ResizeObserver',
+  class {
+    observe = noop
+    unobserve = noop
+    disconnect = noop
+  }
+)
+Element.prototype.scrollIntoView = noop
+Element.prototype.hasPointerCapture = () => false
+Element.prototype.releasePointerCapture = noop
+
+const QC: WorkOrderStatusOption = {
+  id: 'qc',
+  name: 'Quality check',
+  stage: 'completed',
+  color: 'blue',
+  notifyCustomer: false,
+  messageTemplate: null,
+}
+
+function renderStepper(props: Partial<Parameters<typeof StatusStepper>[0]> = {}) {
+  const onChange = vi.fn()
+  render(<StatusStepper status="pending" onChange={onChange} {...props} />)
+  return { onChange, stepper: screen.getByTestId('status-stepper') }
+}
+
+describe('StatusStepper', () => {
+  it('opens the menu of the stage the job is in when that stage is clicked', () => {
+    const { onChange, stepper } = renderStepper({ status: 'in-progress', canAddStatus: true })
+    const current = within(stepper).getByRole('button', { name: 'In Progress' })
+    expect(current).toHaveAttribute('aria-current', 'step')
+    expect(current).toHaveAttribute('aria-haspopup', 'menu')
+
+    fireEvent.click(current)
+
+    const menu = screen.getByRole('menu')
+    expect(within(menu).getByRole('menuitem', { name: 'Waiting Parts' })).toBeInTheDocument()
+    expect(within(menu).getByRole('menuitem', { name: 'Add status' })).toHaveAttribute(
+      'href',
+      '/settings/work-order-statuses'
+    )
+    expect(onChange).not.toHaveBeenCalled()
+
+    fireEvent.click(within(menu).getByRole('menuitem', { name: 'Waiting Parts' }))
+    expect(onChange).toHaveBeenCalledWith('waiting-parts', null)
+  })
+
+  it('opens the same menu from the keyboard', async () => {
+    const user = userEvent.setup()
+    renderStepper({ status: 'in-progress' })
+    const current = screen.getByRole('button', { name: 'In Progress' })
+
+    current.focus()
+    await user.keyboard('{Enter}')
+    expect(screen.getByRole('menuitem', { name: 'Waiting Parts' })).toBeInTheDocument()
+
+    await user.keyboard('{Escape}')
+    expect(screen.queryByRole('menu')).not.toBeInTheDocument()
+    expect(current).toHaveFocus()
+
+    await user.keyboard(' ')
+    expect(screen.getByRole('menuitem', { name: 'Waiting Parts' })).toBeInTheDocument()
+  })
+
+  it('opens the menu with "add a status" only for somebody who may change settings', () => {
+    renderStepper({ status: 'in-progress', canAddStatus: false })
+    fireEvent.click(screen.getByRole('button', { name: 'In Progress' }))
+    expect(screen.getByRole('menuitem', { name: 'Waiting Parts' })).toBeInTheDocument()
+    expect(screen.queryByRole('menuitem', { name: 'Add status' })).not.toBeInTheDocument()
+  })
+
+  it('opens the menu of a current stage with a status shown under it, instead of lifting it', () => {
+    const { onChange } = renderStepper({ status: 'waiting-parts' })
+    fireEvent.click(screen.getByRole('button', { name: 'In Progress: Waiting Parts' }))
+    expect(screen.getByRole('menu')).toBeInTheDocument()
+    expect(onChange).not.toHaveBeenCalled()
+
+    // The plain stage at the top of the menu is how the hold is lifted.
+    fireEvent.click(screen.getByRole('menuitem', { name: 'In Progress' }))
+    expect(onChange).toHaveBeenCalledWith('in-progress', null)
+  })
+
+  it('does not make a current stage without a menu a control', async () => {
+    const user = userEvent.setup()
+    const { onChange, stepper } = renderStepper({ status: 'pending' })
+
+    expect(within(stepper).queryByRole('button', { name: 'Pending' })).not.toBeInTheDocument()
+    const current = within(stepper).getByRole('group', { name: 'Pending' })
+    expect(current).toHaveAttribute('aria-current', 'step')
+    expect(current).not.toHaveAttribute('tabindex')
+    expect(current.className).not.toContain('cursor-pointer')
+
+    fireEvent.click(current)
+    expect(onChange).not.toHaveBeenCalled()
+    expect(screen.queryByRole('menu')).not.toBeInTheDocument()
+
+    // The tab order starts at the next stage.
+    await user.tab()
+    expect(screen.getByRole('button', { name: 'In Progress' })).toHaveFocus()
+  })
+
+  it('makes the completed stage a menu once the workshop files a status under it', () => {
+    renderStepper({ status: 'completed', options: [QC] })
+    fireEvent.click(screen.getByRole('button', { name: 'Completed' }))
+    expect(screen.getByRole('menuitem', { name: 'Quality check' })).toBeInTheDocument()
+  })
+
+  it('still lifts an archived status when its stage has no menu', () => {
+    const { onChange } = renderStepper({
+      status: 'completed',
+      customStatus: { id: 'old', name: 'Old status', color: 'blue' },
+    })
+    fireEvent.click(screen.getByRole('button', { name: 'Completed: Old status' }))
+    expect(onChange).toHaveBeenCalledWith('completed', null)
+  })
+
+  it('moves the job when another stage is clicked, without opening a menu', () => {
+    const { onChange } = renderStepper({ status: 'in-progress' })
+    fireEvent.click(screen.getByRole('button', { name: 'Completed' }))
+    expect(onChange).toHaveBeenCalledWith('completed', null)
+    fireEvent.click(screen.getByRole('button', { name: 'Pending' }))
+    expect(onChange).toHaveBeenCalledWith('pending', null)
+    expect(screen.queryByRole('menu')).not.toBeInTheDocument()
+  })
+
+  // The stepper takes no lock: it moves a locked invoice along too, so the
+  // locked page shows exactly these controls. None is new; the current stage
+  // opens only the menu its arrow already opened, and one control is gone.
+  it.each([
+    ['pending', ['In Progress', 'More statuses', 'Completed']],
+    ['in-progress', ['Pending', 'In Progress', 'More statuses', 'Completed']],
+    ['completed', ['Pending', 'In Progress', 'More statuses']],
+  ])('adds no control on a %s job', (status, names) => {
+    renderStepper({ status })
+    expect(screen.getAllByRole('button').map((b) => b.getAttribute('aria-label'))).toEqual(names)
+  })
+
+  it('keeps the arrow opening the menu', async () => {
+    const user = userEvent.setup()
+    renderStepper({ status: 'pending' })
+    await user.click(screen.getByTestId('status-menu-in-progress'))
+    expect(screen.getByRole('menuitem', { name: 'Waiting Parts' })).toBeInTheDocument()
+  })
+})

+ 111 - 52
src/features/vehicles/Components/service-page/modern/StatusStepper.tsx

@@ -1,6 +1,7 @@
 'use client'
 
 import Link from 'next/link'
+import { useRef, useState } from 'react'
 import { useTranslations } from 'next-intl'
 import { Check, ChevronDown, Plus } from 'lucide-react'
 import {
@@ -70,6 +71,12 @@ export function StatusStepper({
       ? { id: WAITING_PARTS, name: waitingLabel, color: 'amber' }
       : customStatus
 
+  // Which stage's menu is open. The arrow and, for the stage the job is in,
+  // the stage itself open the same menu.
+  const [openMenu, setOpenMenu] = useState<Stage | null>(null)
+  const stageRef = useRef<HTMLButtonElement>(null)
+  const openedFromStage = useRef(false)
+
   return (
     <nav
       aria-label={t('modern.statusLabel')}
@@ -87,61 +94,93 @@ export function StatusStepper({
         const hasMenu = under.length > 0 || stage === 'in-progress'
         const sub = isCurrent ? chosen : null
         const name = sub ? `${label}: ${sub.name}` : label
-        return (
-          <div key={stage} className={cn('flex min-w-0 items-center', !isLast && 'flex-1')}>
-            <button
-              type="button"
-              aria-current={isCurrent ? 'step' : undefined}
-              // Named even where only its number shows, for screen readers and
-              // for the tooltip on a stage whose label is cut short.
-              aria-label={name}
-              title={name}
-              onClick={() => {
-                // Clicking the stage a status sits under goes back to the
-                // plain stage, which is how a hold is lifted.
-                if (!isCurrent || sub) onChange(stage, null)
-              }}
-              // Allowed to shrink, so a long label (or a longer language) is
-              // cut with an ellipsis instead of running into the next stage.
-              className="group/step flex min-w-0 cursor-pointer items-center gap-2 rounded-md py-1 pr-1 outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-default"
+        // The stage the job is in opens its menu when it has one, the same
+        // menu as the arrow beside it. One with a status shown under it but
+        // no menu (an archived status alone under its stage) still lifts it,
+        // as it always has. Otherwise there is nothing to do there, so it is
+        // not a control at all: just the step the job is on.
+        const opensMenu = isCurrent && hasMenu
+        const inert = isCurrent && !hasMenu && !sub
+        const inside = (
+          <>
+            <span
+              className={cn(
+                'flex h-5 w-5 shrink-0 items-center justify-center rounded-full border text-[10px] font-semibold tabular-nums transition-colors',
+                isCurrent &&
+                  'border-primary bg-primary text-primary-foreground ring-4 ring-primary/15',
+                isDone && 'border-primary/60 bg-primary/15 text-primary',
+                !isCurrent &&
+                  !isDone &&
+                  'border-border text-muted-foreground group-hover/step:border-primary/60 group-hover/step:text-foreground group-disabled/step:group-hover/step:border-border group-disabled/step:group-hover/step:text-muted-foreground'
+              )}
             >
+              {isDone ? <Check className="h-3 w-3" aria-hidden="true" /> : i + 1}
+            </span>
+            {/* On a narrow screen only the current stage is named; the
+                markers still say how many there are and where the job is. */}
+            <span
+              className={cn(
+                'min-w-0 truncate py-px text-[13px] leading-none',
+                isCurrent
+                  ? 'font-semibold text-foreground'
+                  : 'hidden text-muted-foreground group-hover/step:text-foreground group-disabled/step:group-hover/step:text-muted-foreground @2xl:inline'
+              )}
+            >
+              {label}
+            </span>
+            {sub && (
               <span
+                data-testid="status-sub"
                 className={cn(
-                  'flex h-5 w-5 shrink-0 items-center justify-center rounded-full border text-[10px] font-semibold tabular-nums transition-colors',
-                  isCurrent &&
-                    'border-primary bg-primary text-primary-foreground ring-4 ring-primary/15',
-                  isDone && 'border-primary/60 bg-primary/15 text-primary',
-                  !isCurrent &&
-                    !isDone &&
-                    'border-border text-muted-foreground group-hover/step:border-primary/60 group-hover/step:text-foreground group-disabled/step:group-hover/step:border-border group-disabled/step:group-hover/step:text-muted-foreground'
+                  'min-w-0 truncate rounded-full border px-2 py-0.5 text-[12px] font-medium leading-none',
+                  statusColorClasses(sub.color).chip
                 )}
               >
-                {isDone ? <Check className="h-3 w-3" aria-hidden="true" /> : i + 1}
+                {sub.name}
               </span>
-              {/* On a narrow screen only the current stage is named; the
-                  markers still say how many there are and where the job is. */}
-              <span
-                className={cn(
-                  'min-w-0 truncate py-px text-[13px] leading-none',
-                  isCurrent
-                    ? 'font-semibold text-foreground'
-                    : 'hidden text-muted-foreground group-hover/step:text-foreground group-disabled/step:group-hover/step:text-muted-foreground @2xl:inline'
-                )}
+            )}
+          </>
+        )
+        return (
+          <div key={stage} className={cn('flex min-w-0 items-center', !isLast && 'flex-1')}>
+            {inert ? (
+              <div
+                role="group"
+                aria-current="step"
+                aria-label={name}
+                title={name}
+                className="flex min-w-0 items-center gap-2 py-1 pr-1"
               >
-                {label}
-              </span>
-              {sub && (
-                <span
-                  data-testid="status-sub"
-                  className={cn(
-                    'min-w-0 truncate rounded-full border px-2 py-0.5 text-[12px] font-medium leading-none',
-                    statusColorClasses(sub.color).chip
-                  )}
-                >
-                  {sub.name}
-                </span>
-              )}
-            </button>
+                {inside}
+              </div>
+            ) : (
+              <button
+                ref={opensMenu ? stageRef : undefined}
+                type="button"
+                aria-current={isCurrent ? 'step' : undefined}
+                aria-haspopup={opensMenu ? 'menu' : undefined}
+                aria-expanded={opensMenu ? openMenu === stage : undefined}
+                // Named even where only its number shows, for screen readers and
+                // for the tooltip on a stage whose label is cut short.
+                aria-label={name}
+                title={name}
+                onClick={() => {
+                  if (opensMenu) {
+                    openedFromStage.current = true
+                    setOpenMenu(stage)
+                    return
+                  }
+                  // Clicking the stage a status sits under goes back to the
+                  // plain stage, which is how a hold is lifted.
+                  if (!isCurrent || sub) onChange(stage, null)
+                }}
+                // Allowed to shrink, so a long label (or a longer language) is
+                // cut with an ellipsis instead of running into the next stage.
+                className="group/step flex min-w-0 cursor-pointer items-center gap-2 rounded-md py-1 pr-1 outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-default"
+              >
+                {inside}
+              </button>
+            )}
 
             {hasMenu && (
               <StageMenu
@@ -154,6 +193,17 @@ export function StatusStepper({
                 chosenId={sub?.id ?? null}
                 isCurrent={isCurrent}
                 onChange={onChange}
+                open={openMenu === stage}
+                onOpenChange={(open) => {
+                  if (open) openedFromStage.current = false
+                  setOpenMenu(open ? stage : null)
+                }}
+                onCloseAutoFocus={(event) => {
+                  // Opened from the stage, focus goes back to the stage.
+                  if (!openedFromStage.current) return
+                  event.preventDefault()
+                  stageRef.current?.focus()
+                }}
               />
             )}
 
@@ -173,8 +223,11 @@ export function StatusStepper({
   )
 }
 
-/** The arrow beside a stage, and the statuses filed under it. */
-function StageMenu({
+/**
+ * The arrow beside a stage, and the statuses filed under it. Uncontrolled
+ * unless `open` is passed, so it can be used on its own.
+ */
+export function StageMenu({
   stage,
   stageLabel,
   waitingLabel,
@@ -184,6 +237,9 @@ function StageMenu({
   chosenId,
   isCurrent,
   onChange,
+  open,
+  onOpenChange,
+  onCloseAutoFocus,
 }: {
   stage: Stage
   stageLabel: string
@@ -195,13 +251,16 @@ function StageMenu({
   chosenId: string | null
   isCurrent: boolean
   onChange: (status: string, custom: WorkOrderStatusOption | null) => void
+  open?: boolean
+  onOpenChange?: (open: boolean) => void
+  onCloseAutoFocus?: (event: Event) => void
 }) {
   const row = 'flex cursor-pointer items-center gap-2 text-[13px]'
   const tick = (on: boolean) => (
     <Check className={cn('ml-auto h-3.5 w-3.5', on ? 'opacity-100' : 'opacity-0')} />
   )
   return (
-    <DropdownMenu>
+    <DropdownMenu open={open} onOpenChange={onOpenChange}>
       <DropdownMenuTrigger asChild>
         <button
           type="button"
@@ -215,7 +274,7 @@ function StageMenu({
           <ChevronDown className="h-3.5 w-3.5" aria-hidden="true" />
         </button>
       </DropdownMenuTrigger>
-      <DropdownMenuContent align="start" className="min-w-52">
+      <DropdownMenuContent align="start" className="min-w-52" onCloseAutoFocus={onCloseAutoFocus}>
         <DropdownMenuItem className={row} onSelect={() => onChange(stage, null)}>
           <span className="h-2 w-2 shrink-0 rounded-full bg-primary" />
           {stageLabel}