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

Redraw only the edited card when typing on a work order (#666)

* Add a hook for handlers that keep their identity

* Draw only the edited line in the labour and parts editors

* Stop the work order redrawing every card on each keystroke

* Let Unpaid in the work order header take a payment, and stop the read-only pills looking like controls

* Swap a stable handler in when its render commits, not while rendering

* Put the cursor in Amount once the payment form is drawn
Bernt Christian Egeland 5 дней назад
Родитель
Сommit
6f110cb2ca

+ 151 - 0
src/__tests__/features/vehicles/line-editor-rows.test.tsx

@@ -0,0 +1,151 @@
+/**
+ * The rows of the labour and parts editors.
+ *
+ * A work order with twenty lines used to draw all twenty again for every
+ * character typed into one of them, which is most of why the page answered
+ * slowly. A row is now drawn again only when its own line changes, and its
+ * buttons name the line by its place in the list. So: the right line still
+ * goes when one is deleted, typing after that still lands in the line under
+ * the cursor, and the other lines are left alone while one is typed in.
+ */
+
+import { fireEvent, render, screen } from '@testing-library/react'
+import { useCallback, useState } from 'react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { TooltipProvider } from '@/components/ui/tooltip'
+import { LaborEditor } from '@/features/vehicles/Components/service-edit/LaborEditor'
+import { PartsEditor } from '@/features/vehicles/Components/service-edit/PartsEditor'
+import type { ServiceLaborInput, ServicePartInput } from '@/features/vehicles/Schema/serviceSchema'
+
+// Every row draws one drag handle, so this counts how often rows are drawn.
+const drawn = vi.hoisted(() => ({ rows: 0 }))
+const openInventory = vi.fn()
+vi.mock('@/components/line-drag-handle', () => ({
+  LineDragHandle: () => {
+    drawn.rows += 1
+    return null
+  },
+}))
+
+const labor = (description: string): ServiceLaborInput => ({
+  description,
+  hours: 1,
+  rate: 100,
+  total: 100,
+  pricingType: 'hourly',
+})
+const part = (name: string): ServicePartInput => ({
+  name,
+  partNumber: '',
+  quantity: 1,
+  unitPrice: 10,
+  total: 10,
+  unitCost: 0,
+  markupPercent: 0,
+})
+
+function LaborHarness() {
+  const [items, setItems] = useState([labor('Brakes'), labor('Oil change'), labor('Alignment')])
+  const update = useCallback(
+    (index: number, field: keyof ServiceLaborInput, value: string | number) =>
+      setItems((prev) => prev.map((row, i) => (i === index ? { ...row, [field]: value } : row))),
+    []
+  )
+  return (
+    <TooltipProvider>
+      <LaborEditor
+        laborItems={items}
+        setLaborItems={setItems}
+        updateLabor={update}
+        laborSubtotal={0}
+        currencyCode="USD"
+        defaultLaborRate={100}
+      />
+    </TooltipProvider>
+  )
+}
+
+function PartsHarness() {
+  const [items, setItems] = useState([part('Pads'), part('Filter'), part('Wiper')])
+  const update = useCallback(
+    (index: number, field: keyof ServicePartInput, value: string | number) =>
+      setItems((prev) => prev.map((row, i) => (i === index ? { ...row, [field]: value } : row))),
+    []
+  )
+  return (
+    <TooltipProvider>
+      <PartsEditor
+        partItems={items}
+        setPartItems={setItems}
+        updatePart={update}
+        partsSubtotal={0}
+        currencyCode="USD"
+        hasInventory={false}
+        onOpenInventory={openInventory}
+      />
+    </TooltipProvider>
+  )
+}
+
+const descriptions = () =>
+  screen.getAllByPlaceholderText('Description *').map((el) => (el as HTMLTextAreaElement).value)
+const names = () =>
+  screen.getAllByPlaceholderText('Name *').map((el) => (el as HTMLTextAreaElement).value)
+
+beforeEach(() => {
+  drawn.rows = 0
+})
+
+describe('labour lines', () => {
+  it('deletes the line whose button was pressed', () => {
+    render(<LaborHarness />)
+    fireEvent.click(screen.getAllByRole('button', { name: 'Delete row' })[1])
+    expect(descriptions()).toEqual(['Brakes', 'Alignment'])
+  })
+
+  it('types into the line under the cursor after one above it is deleted', () => {
+    render(<LaborHarness />)
+    fireEvent.click(screen.getAllByRole('button', { name: 'Delete row' })[0])
+    fireEvent.change(screen.getAllByPlaceholderText('Description *')[1], {
+      target: { value: 'Alignment, four wheels' },
+    })
+    expect(descriptions()).toEqual(['Oil change', 'Alignment, four wheels'])
+  })
+
+  it('draws only the line being typed in', () => {
+    render(<LaborHarness />)
+    drawn.rows = 0
+    fireEvent.change(screen.getAllByPlaceholderText('Description *')[0], {
+      target: { value: 'Brakes, front' },
+    })
+    expect(descriptions()).toEqual(['Brakes, front', 'Oil change', 'Alignment'])
+    expect(drawn.rows).toBe(1)
+  })
+})
+
+describe('part lines', () => {
+  it('deletes the line whose button was pressed', () => {
+    render(<PartsHarness />)
+    fireEvent.click(screen.getAllByRole('button', { name: 'Delete row' })[1])
+    expect(names()).toEqual(['Pads', 'Wiper'])
+  })
+
+  it('types into the line under the cursor after one above it is deleted', () => {
+    render(<PartsHarness />)
+    fireEvent.click(screen.getAllByRole('button', { name: 'Delete row' })[0])
+    fireEvent.change(screen.getAllByPlaceholderText('Name *')[1], {
+      target: { value: 'Wiper blade' },
+    })
+    expect(names()).toEqual(['Filter', 'Wiper blade'])
+  })
+
+  it('draws only the line being typed in', () => {
+    render(<PartsHarness />)
+    drawn.rows = 0
+    fireEvent.change(screen.getAllByPlaceholderText('Name *')[0], {
+      target: { value: 'Pads, front' },
+    })
+    expect(names()).toEqual(['Pads, front', 'Filter', 'Wiper'])
+    expect(drawn.rows).toBe(1)
+  })
+})

+ 72 - 0
src/__tests__/features/vehicles/take-payment-focus.test.tsx

@@ -0,0 +1,72 @@
+/**
+ * "Take payment" on the work order's money bar opens the payment form and
+ * puts the cursor in Amount, so the figure can be typed at once.
+ *
+ * The form used to be asked for and the cursor placed in the same breath, on
+ * the next animation frame. React draws the form a moment after it is asked
+ * for, and nothing promises that moment comes before the frame: when the
+ * frame came first there was no Amount field to focus, and the cursor stayed
+ * on the button. The frame is run early here, which is that case.
+ */
+
+import { render, screen } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { WorkOrderLayoutProvider } from '@/components/work-order-layout-context'
+import { PaymentsSection } from '@/features/vehicles/Components/service-detail/PaymentsSection'
+
+const noop = vi.fn()
+
+function Section({ signal }: { signal: number }) {
+  return (
+    <WorkOrderLayoutProvider value={true}>
+      <PaymentsSection
+        payments={[]}
+        paymentStatus="unpaid"
+        manuallyPaid={false}
+        totalPaid={0}
+        displayTotal={250}
+        balanceDue={250}
+        currencyCode="USD"
+        onCreatePayment={async () => true}
+        onDeletePayment={noop}
+        onTogglePaid={noop}
+        paymentLoading={false}
+        deletingPayment={null}
+        openFormSignal={signal}
+      />
+    </WorkOrderLayoutProvider>
+  )
+}
+
+describe('the payment form opened from the money bar', () => {
+  beforeEach(() => {
+    // The frame arrives before React has drawn anything it was just asked for.
+    vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
+      callback(0)
+      return 0
+    })
+    Element.prototype.scrollIntoView = vi.fn()
+  })
+  afterEach(() => {
+    vi.unstubAllGlobals()
+  })
+
+  it('stays closed until it is asked for', () => {
+    render(<Section signal={0} />)
+    expect(document.getElementById('paymentAmount')).toBeNull()
+  })
+
+  it('opens with the cursor in Amount', () => {
+    const { rerender } = render(<Section signal={0} />)
+    rerender(<Section signal={1} />)
+    expect(screen.getByLabelText('Amount')).toHaveFocus()
+  })
+
+  it('takes the cursor back to Amount when asked again with the form open', () => {
+    const { rerender } = render(<Section signal={0} />)
+    rerender(<Section signal={1} />)
+    screen.getByLabelText('Note').focus()
+    rerender(<Section signal={2} />)
+    expect(screen.getByLabelText('Amount')).toHaveFocus()
+  })
+})

+ 48 - 0
src/__tests__/hooks/use-stable-callback.test.ts

@@ -0,0 +1,48 @@
+/**
+ * A handler handed to a memoized part of a page must stay the same function,
+ * or that part is drawn again on every render; and it must still do what the
+ * newest render says, or a click acts on what the page showed a moment ago.
+ */
+
+import { act, render, renderHook } from '@testing-library/react'
+import { createElement, startTransition, Suspense } from 'react'
+import { describe, expect, it } from 'vitest'
+import { useStableCallback } from '@/hooks/use-stable-callback'
+
+describe('useStableCallback', () => {
+  it('stays the same function while what it does follows the latest render', () => {
+    const { result, rerender } = renderHook(
+      ({ status }: { status: string }) => useStableCallback((suffix: string) => status + suffix),
+      { initialProps: { status: 'pending' } }
+    )
+    const first = result.current
+    expect(first('!')).toBe('pending!')
+
+    rerender({ status: 'completed' })
+
+    expect(result.current).toBe(first)
+    expect(first('!')).toBe('completed!')
+  })
+
+  it('keeps the handler of the page on screen when a newer render is abandoned', () => {
+    let handler: () => string = () => ''
+    const never = new Promise<never>(() => undefined)
+    function Probe({ status, suspend }: { status: string; suspend: boolean }) {
+      handler = useStableCallback(() => status)
+      // A render that never finishes: React keeps showing the one before it.
+      if (suspend) throw never
+      return null
+    }
+    const tree = (status: string, suspend: boolean) =>
+      createElement(Suspense, { fallback: null }, createElement(Probe, { status, suspend }))
+
+    const { rerender } = render(tree('pending', false))
+    expect(handler()).toBe('pending')
+
+    act(() => {
+      startTransition(() => rerender(tree('completed', true)))
+    })
+
+    expect(handler()).toBe('pending')
+  })
+})

+ 23 - 9
src/features/fault-codes/Components/FaultCodesOnJob.tsx

@@ -1,6 +1,14 @@
 'use client'
 
-import { createContext, type ReactNode, useCallback, useContext, useEffect, useState } from 'react'
+import {
+  createContext,
+  type ReactNode,
+  useCallback,
+  useContext,
+  useEffect,
+  useMemo,
+  useState,
+} from 'react'
 import { useRouter } from 'next/navigation'
 import { useTranslations } from 'next-intl'
 import { History, RefreshCw } from 'lucide-react'
@@ -64,14 +72,20 @@ export function FaultCodesJobProvider({
 }) {
   const [entryOpen, setEntryOpen] = useState(false)
   const [sheetCode, setSheetCode] = useState<string | null>(null)
-  const value: JobFaultCodes = {
-    ...info,
-    vehicleId,
-    serviceRecordId,
-    locked,
-    openEntry: () => setEntryOpen(true),
-    openCode: setSheetCode,
-  }
+  // One object while nothing in it changes: the labour card and the findings
+  // read it, and a new one on each render of the page drew them again for
+  // every character typed anywhere on the work order.
+  const value: JobFaultCodes = useMemo(
+    () => ({
+      ...info,
+      vehicleId,
+      serviceRecordId,
+      locked,
+      openEntry: () => setEntryOpen(true),
+      openCode: setSheetCode,
+    }),
+    [info, vehicleId, serviceRecordId, locked]
+  )
   return (
     <Ctx.Provider value={value}>
       {children}

+ 12 - 2
src/features/vehicles/Components/service-detail/PaymentsSection.tsx

@@ -80,12 +80,22 @@ export function PaymentsSection({
   useEffect(() => {
     if (openFormSignal === 0) return
     setShowForm(true)
-    // After the form has been drawn, so the view lands on it and not above it.
+  }, [openFormSignal])
+
+  // The signal the view and the cursor were last moved for. Moved in an
+  // effect of their own, which runs once the form is in the page: asked for
+  // in the same breath as the form, on the next frame, the frame could come
+  // before React had drawn the form, and the cursor stayed on the button.
+  const answeredSignal = useRef(0)
+  useEffect(() => {
+    if (!showForm || answeredSignal.current === openFormSignal) return
+    answeredSignal.current = openFormSignal
+    // After the form has been laid out, so the view lands on it and not above it.
     requestAnimationFrame(() => {
       sectionRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' })
       formRef.current?.querySelector<HTMLInputElement>('[name="paymentAmount"]')?.focus()
     })
-  }, [openFormSignal])
+  }, [showForm, openFormSignal])
 
   const handleSubmit = async () => {
     if (!formRef.current) return

+ 29 - 17
src/features/vehicles/Components/service-edit/LaborEditor.tsx

@@ -5,7 +5,7 @@ import { ShopFeeTag, useShopFeeLocked } from '@/features/settings/Components/Sho
 import { LineTaxToggle } from '@/features/settings/Components/LineTaxToggle'
 import { useLineTax } from '@/features/settings/Components/LineTaxContext'
 import { laborTaxable } from '@/lib/taxable-lines'
-import { useRef, useCallback, useState, useEffect } from 'react'
+import { memo, useRef, useCallback, useState, useEffect } from 'react'
 import { Button } from '@/components/ui/button'
 import { Input } from '@/components/ui/input'
 import { Textarea } from '@/components/ui/textarea'
@@ -73,7 +73,17 @@ interface LaborEditorProps {
   guideStock?: LaborGuideStock
 }
 
-function SortableLaborRow({
+// Stable, so the drag context keeps its identity between renders and a row
+// that did not change is not drawn again.
+const POINTER_SENSOR_OPTIONS = { activationConstraint: { distance: 5 } }
+const KEYBOARD_SENSOR_OPTIONS = { coordinateGetter: sortableKeyboardCoordinates }
+
+/**
+ * Memoized: typing in one line used to draw every line of the job again. A
+ * row is drawn again only when its own line, or its place in the list, changes,
+ * which is why the handlers take the index instead of closing over it.
+ */
+const SortableLaborRow = memo(function SortableLaborRow({
   id,
   labor,
   index,
@@ -82,22 +92,23 @@ function SortableLaborRow({
   onToggleTax,
   currencyCode,
   rateLabel,
-  t,
   dragEnabled,
 }: {
   id: string
   labor: ServiceLaborInput
   index: number
   updateLabor: (index: number, field: keyof ServiceLaborInput, value: string | number) => void
-  onDelete: () => void
+  onDelete: (index: number) => void
   /** Flips whether the job's tax is charged on this line. */
-  onToggleTax: () => void
+  onToggleTax: (index: number) => void
   currencyCode: string
   /** Pre-formatted "Rate (kr/hr)" header, which needs the currency symbol. */
   rateLabel: string
-  t: (key: string) => string
   dragEnabled: boolean
 }) {
+  // Read here, not handed down: a prop has to keep its identity for the row
+  // to be left alone, and nothing promises that of a translator.
+  const t = useTranslations('service.labor')
   const formatCurrency = useFormatCurrency()
   const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
     id,
@@ -163,7 +174,10 @@ function SortableLaborRow({
               {isService ? t('serviceTag') : t('hourlyTag')}
             </button>
           )}
-          <LineTaxToggle taxable={laborTaxable(labor, applies)} onToggle={onToggleTax} />
+          <LineTaxToggle
+            taxable={laborTaxable(labor, applies)}
+            onToggle={() => onToggleTax(index)}
+          />
         </div>
         <FieldRow label={isService || isFee ? t('qty') : t('hours')}>
           <Input
@@ -198,7 +212,7 @@ function SortableLaborRow({
             variant="ghost"
             size="icon"
             className="h-9 w-9 shrink-0 text-muted-foreground hover:text-destructive"
-            onClick={onDelete}
+            onClick={() => onDelete(index)}
             aria-label={t('deleteRow')}
           >
             <Trash2 className="h-4 w-4" />
@@ -207,7 +221,7 @@ function SortableLaborRow({
       </div>
     </div>
   )
-}
+})
 
 export function LaborEditor({
   laborItems,
@@ -247,8 +261,8 @@ export function LaborEditor({
   }
 
   const sensors = useSensors(
-    useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
-    useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
+    useSensor(PointerSensor, POINTER_SENSOR_OPTIONS),
+    useSensor(KeyboardSensor, KEYBOARD_SENSOR_OPTIONS)
   )
 
   const handleDragEnd = useCallback(
@@ -424,11 +438,10 @@ export function LaborEditor({
                     labor={labor}
                     index={i}
                     updateLabor={updateLabor}
-                    onDelete={() => deleteLabor(i)}
-                    onToggleTax={() => toggleLaborTax(i)}
+                    onDelete={deleteLabor}
+                    onToggleTax={toggleLaborTax}
                     currencyCode={currencyCode}
                     rateLabel={t('rate', { currency: cs })}
-                    t={t}
                     dragEnabled
                   />
                 ))}
@@ -442,11 +455,10 @@ export function LaborEditor({
                 labor={labor}
                 index={i}
                 updateLabor={updateLabor}
-                onDelete={() => deleteLabor(i)}
-                onToggleTax={() => toggleLaborTax(i)}
+                onDelete={deleteLabor}
+                onToggleTax={toggleLaborTax}
                 currencyCode={currencyCode}
                 rateLabel={t('rate', { currency: cs })}
-                t={t}
                 dragEnabled={false}
               />
             ))

+ 32 - 18
src/features/vehicles/Components/service-edit/PartsEditor.tsx

@@ -1,6 +1,6 @@
 'use client'
 
-import { useRef, useCallback, useState, useEffect, useId, useMemo } from 'react'
+import { memo, useRef, useCallback, useState, useEffect, useId, useMemo } from 'react'
 import { Button } from '@/components/ui/button'
 import { Input } from '@/components/ui/input'
 import { Textarea } from '@/components/ui/textarea'
@@ -69,7 +69,19 @@ interface PartsEditorProps {
   markupAppliesToInventory?: boolean
 }
 
-function SortablePartRow({
+const NO_INVENTORY: PartSuggestion[] = []
+
+// Stable, so the drag context keeps its identity between renders and a row
+// that did not change is not drawn again.
+const POINTER_SENSOR_OPTIONS = { activationConstraint: { distance: 5 } }
+const KEYBOARD_SENSOR_OPTIONS = { coordinateGetter: sortableKeyboardCoordinates }
+
+/**
+ * Memoized: typing in one line used to draw every line of the job again. A
+ * row is drawn again only when its own line, or its place in the list, changes,
+ * which is why the handlers take the index instead of closing over it.
+ */
+const SortablePartRow = memo(function SortablePartRow({
   id,
   part,
   index,
@@ -77,7 +89,6 @@ function SortablePartRow({
   onDelete,
   onToggleTax,
   currencyCode,
-  t,
   dragEnabled,
   inventoryParts,
   onSelectSuggestion,
@@ -96,17 +107,19 @@ function SortablePartRow({
     value: string | number,
     options?: { commit?: boolean }
   ) => void
-  onDelete: () => void
+  onDelete: (index: number) => void
   /** Flips whether the job's tax is charged on this line. */
-  onToggleTax: () => void
+  onToggleTax: (index: number) => void
   currencyCode: string
   inventoryParts: PartSuggestion[]
   onSelectSuggestion: (index: number, part: PartSuggestion) => void
   defaultMarkupPercent: number
   markupAppliesToInventory: boolean
-  t: (key: string) => string
   dragEnabled: boolean
 }) {
+  // Read here, not handed down: a prop has to keep its identity for the row
+  // to be left alone, and nothing promises that of a translator.
+  const t = useTranslations('service.parts')
   const formatCurrency = useFormatCurrency()
   const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
     id,
@@ -184,7 +197,10 @@ function SortablePartRow({
                 onSelect={(picked) => onSelectSuggestion(index, picked)}
               />
             </div>
-            <LineTaxToggle taxable={partTaxable(part, applies)} onToggle={onToggleTax} />
+            <LineTaxToggle
+              taxable={partTaxable(part, applies)}
+              onToggle={() => onToggleTax(index)}
+            />
           </div>
         </FieldRow>
         <FieldRow label={t('qty')}>
@@ -256,7 +272,7 @@ function SortablePartRow({
             variant="ghost"
             size="icon"
             className="h-9 w-9 shrink-0 text-muted-foreground hover:text-destructive"
-            onClick={onDelete}
+            onClick={() => onDelete(index)}
             aria-label={t('deleteRow')}
           >
             <Trash2 className="h-4 w-4" />
@@ -265,7 +281,7 @@ function SortablePartRow({
       </div>
     </div>
   )
-}
+})
 
 export function PartsEditor({
   partItems,
@@ -274,7 +290,7 @@ export function PartsEditor({
   partsSubtotal,
   currencyCode,
   hasInventory,
-  inventoryParts = [],
+  inventoryParts = NO_INVENTORY,
   onOpenInventory,
   onScanBarcode,
   defaultMarkupPercent = 0,
@@ -343,8 +359,8 @@ export function PartsEditor({
   }
 
   const sensors = useSensors(
-    useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
-    useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
+    useSensor(PointerSensor, POINTER_SENSOR_OPTIONS),
+    useSensor(KeyboardSensor, KEYBOARD_SENSOR_OPTIONS)
   )
 
   const handleDragEnd = useCallback(
@@ -471,10 +487,9 @@ export function PartsEditor({
                     part={part}
                     index={i}
                     updatePart={updatePart}
-                    onDelete={() => deletePart(i)}
-                    onToggleTax={() => togglePartTax(i)}
+                    onDelete={deletePart}
+                    onToggleTax={togglePartTax}
                     currencyCode={currencyCode}
-                    t={t}
                     dragEnabled
                     inventoryParts={inventoryParts}
                     onSelectSuggestion={handleSelectSuggestion}
@@ -493,10 +508,9 @@ export function PartsEditor({
                 part={part}
                 index={i}
                 updatePart={updatePart}
-                onDelete={() => deletePart(i)}
-                onToggleTax={() => togglePartTax(i)}
+                onDelete={deletePart}
+                onToggleTax={togglePartTax}
                 currencyCode={currencyCode}
-                t={t}
                 dragEnabled={false}
                 inventoryParts={inventoryParts}
                 onSelectSuggestion={handleSelectSuggestion}

+ 191 - 98
src/features/vehicles/Components/service-page/ServicePageClient.tsx

@@ -12,7 +12,7 @@ import { setInvoiceEditUnlocked } from '@/features/settings/Actions/documentLock
 import { InvoiceDesignMenu } from './InvoiceDesignMenu'
 import { PayCodeButton } from './PayCodeButton'
 import type { WorkOrderStatusOption } from '@/features/work-order-statuses/Lib/stages'
-import { useState, useCallback, useMemo, useRef, useEffect, type ReactNode } from 'react'
+import { memo, useState, useCallback, useMemo, useRef, useEffect, type ReactNode } from 'react'
 import { useRouter } from 'next/navigation'
 import { sendInvoiceEmail } from '@/features/email/Actions/emailActions'
 import {
@@ -31,6 +31,7 @@ import { InventoryPickerDialog } from '../service-edit/InventoryPickerDialog'
 import { BarcodeScannerDialog } from '@/components/barcode-scanner-dialog'
 import { useHardwareScanner } from '@/hooks/use-hardware-scanner'
 import { useSaveShortcut } from '@/hooks/use-save-shortcut'
+import { useStableCallback } from '@/hooks/use-stable-callback'
 import { lookupPartByBarcode } from '@/features/inventory/Actions/lookupPartByBarcode'
 import { toast } from 'sonner'
 import { Button } from '@/components/ui/button'
@@ -69,7 +70,7 @@ import { PresenceChips } from '@/features/realtime/Components/PresenceChips'
 import { ModernDetails } from './modern/ModernDetails'
 import { useCustomerReferenceEnabled } from '@/components/customer-reference-context'
 import { referenceMissing } from '@/features/customer-reference/Lib/reference'
-import { ModernHero } from './modern/ModernHero'
+import { ModernHero as ModernHeroBase } from './modern/ModernHero'
 import { revealRequiredMeters } from '@/features/meters/Lib/requiredMetersReveal'
 import type { WorkOrderJobProps, WorkOrderSidebarProps } from './modern/details-props'
 import { lineTotal, resolvePartPrice } from '@/features/inventory/Lib/partPricing'
@@ -77,6 +78,13 @@ import { vehicleName } from '@/lib/vehicle-name'
 
 export type { ServicePageClientProps, BoardTechnicianOption } from './service-page-types'
 
+/**
+ * Memoized, with the handlers below kept stable for it: the form's state
+ * lives in this component, so it renders on every keystroke in a line, and
+ * the header shows nothing of what is typed there.
+ */
+const ModernHero = memo(ModernHeroBase)
+
 export function ServicePageClient({
   record,
   vehicleId,
@@ -504,62 +512,139 @@ export function ServicePageClient({
     actions.setShowShareDialog(true)
   }
 
-  // Status reports are a section under the job, outside the form.
-  const statusReportList = (
-    <StatusReportList
-      serviceRecordId={record.id}
-      organizationId={organizationId}
-      vehicleName={formState.vehicleName}
-      customer={
-        customer
-          ? {
-              id: customer.id,
-              name: customer.name,
-              email: customer.email,
-              phone: customer.phone,
-              telegramChatId: customer.telegramChatId || null,
-            }
-          : null
-      }
-      smsEnabled={smsEnabled}
-      emailEnabled={emailEnabled}
-      telegramEnabled={telegramEnabled}
-      initialReports={statusReports}
-    />
+  // Status reports are a section under the job, outside the form. Built once
+  // per change of what they show, so the files card they sit in is not drawn
+  // again on every keystroke elsewhere on the page.
+  const reportsVehicleName = formState.vehicleName
+  const statusReportList = useMemo(
+    () => (
+      <StatusReportList
+        serviceRecordId={record.id}
+        organizationId={organizationId}
+        vehicleName={reportsVehicleName}
+        customer={
+          customer
+            ? {
+                id: customer.id,
+                name: customer.name,
+                email: customer.email,
+                phone: customer.phone,
+                telegramChatId: customer.telegramChatId || null,
+              }
+            : null
+        }
+        smsEnabled={smsEnabled}
+        emailEnabled={emailEnabled}
+        telegramEnabled={telegramEnabled}
+        initialReports={statusReports}
+      />
+    ),
+    [
+      record.id,
+      organizationId,
+      reportsVehicleName,
+      customer,
+      smsEnabled,
+      emailEnabled,
+      telegramEnabled,
+      statusReports,
+    ]
+  )
+  const statusReportsSection = useMemo(
+    () => ({ count: statusReports.length, list: statusReportList }),
+    [statusReports.length, statusReportList]
   )
 
-  // What can be done with the job as a whole, drawn in the header.
-  const headerActionProps = {
-    meetingUrl: videoCall.link?.url ?? null,
-    downloading: actions.downloading,
-    saving: formState.loading,
-    hasUnsavedChanges: formState.hasUnsavedChanges,
-    showSaved: formState.showSaved,
-    onDownloadPDF: async () => {
-      if (!(await checkDates())) return
-      if (formState.hasUnsavedChanges) await actions.saveNow()
-      actions.handleDownloadPDF()
-    },
-    onPreviewPDF: previewInvoice,
-    // The sheet says the job as it stands, so what has been typed goes in first.
-    onPrintWorkOrder: async () => {
-      if (formState.hasUnsavedChanges) await actions.saveNow()
-      setShowWorkOrderPreview(true)
-    },
-    onDelete: actions.handleDelete,
-    onShowEmail: async () => {
-      if (!checkReference()) return
-      if (!(await checkDates())) return
-      if (formState.hasUnsavedChanges) await actions.saveNow()
-      actions.setShowEmailDialog(true)
-    },
-    onShowShare: shareInvoice,
-    onNotifyCustomer: handleNotifyCustomer,
-    hasCustomer: !!customer,
-    designMenu: canChangeIssuedDesign ? (
-      <InvoiceDesignMenu recordId={record.id} designFollowsName={designFollowsName} />
-    ) : undefined,
-  }
+  // What can be done with the job as a whole, drawn in the header. Each
+  // handler keeps its identity and runs its latest version, so the header is
+  // drawn again only when what it shows changes.
+  const onDownloadPDF = useStableCallback(async () => {
+    if (!(await checkDates())) return
+    if (formState.hasUnsavedChanges) await actions.saveNow()
+    actions.handleDownloadPDF()
+  })
+  const onPreviewPDF = useStableCallback(previewInvoice)
+  // The sheet says the job as it stands, so what has been typed goes in first.
+  const onPrintWorkOrder = useStableCallback(async () => {
+    if (formState.hasUnsavedChanges) await actions.saveNow()
+    setShowWorkOrderPreview(true)
+  })
+  const onDelete = useStableCallback(actions.handleDelete)
+  const onShowEmail = useStableCallback(async () => {
+    if (!checkReference()) return
+    if (!(await checkDates())) return
+    if (formState.hasUnsavedChanges) await actions.saveNow()
+    actions.setShowEmailDialog(true)
+  })
+  const onShowShare = useStableCallback(shareInvoice)
+  const onNotifyCustomer = useStableCallback(handleNotifyCustomer)
+  const meetingUrl = videoCall.link?.url ?? null
+  const hasCustomer = !!customer
+  const headerDownloading = actions.downloading
+  const headerSaving = formState.loading
+  const headerUnsaved = formState.hasUnsavedChanges
+  const headerSaved = formState.showSaved
+  const heroActions = useMemo(
+    () => (
+      <>
+        <PresenceChips kind="serviceRecord" id={record.id} className="mr-1" />
+        <ServiceHeaderActions
+          showSave
+          meetingUrl={meetingUrl}
+          downloading={headerDownloading}
+          saving={headerSaving}
+          hasUnsavedChanges={headerUnsaved}
+          showSaved={headerSaved}
+          onDownloadPDF={onDownloadPDF}
+          onPreviewPDF={onPreviewPDF}
+          onPrintWorkOrder={onPrintWorkOrder}
+          onDelete={onDelete}
+          onShowEmail={onShowEmail}
+          onShowShare={onShowShare}
+          onNotifyCustomer={onNotifyCustomer}
+          hasCustomer={hasCustomer}
+          designMenu={
+            canChangeIssuedDesign ? (
+              <InvoiceDesignMenu recordId={record.id} designFollowsName={designFollowsName} />
+            ) : undefined
+          }
+        />
+      </>
+    ),
+    [
+      record.id,
+      meetingUrl,
+      headerDownloading,
+      headerSaving,
+      headerUnsaved,
+      headerSaved,
+      onDownloadPDF,
+      onPreviewPDF,
+      onPrintWorkOrder,
+      onDelete,
+      onShowEmail,
+      onShowShare,
+      onNotifyCustomer,
+      hasCustomer,
+      canChangeIssuedDesign,
+      designFollowsName,
+    ]
+  )
+  const onTitleChange = useStableCallback((next: string) => {
+    setTitle(next)
+    // Saved the moment the field is left, on its own, not with the
+    // form's autosave five seconds later: a rename followed by the
+    // back arrow inside those seconds was lost. Only a refused save
+    // marks the form dirty, so the ordinary path can try again.
+    void updateServiceRecordTitle(record.id, next).then((result) => {
+      if (result.success) {
+        formState.flashSaved()
+      } else {
+        toast.error(result.error || t('page.failedUpdate'))
+        formState.markDirty()
+      }
+    })
+  })
 
   // The invoice's link as a code for the customer at the desk. One element,
   // drawn wherever a payment is taken: beside "Record payment" and on the
@@ -575,6 +660,28 @@ export function ServicePageClient({
     />
   ) : null
 
+  // Handlers for the memoized sections of the body: the same function on
+  // every render, or each keystroke would draw every section again.
+  const { setShowPresetPicker, setShowBarcodeScanner } = formState
+  const onOpenPresets = useCallback(() => setShowPresetPicker(true), [setShowPresetPicker])
+  const onScanBarcode = useCallback(() => setShowBarcodeScanner(true), [setShowBarcodeScanner])
+  const onAddFinding = useCallback(() => obsControlsRef.current?.onAddFinding(), [])
+  const onEditFinding = useCallback<NonNullable<WorkOrderJobProps['onEditFinding']>>(
+    (f) => obsControlsRef.current?.onEditFinding(f),
+    []
+  )
+  const onShowExistingObservations = useCallback(
+    () => obsControlsRef.current?.onShowExistingObservations(),
+    []
+  )
+  const onAddFindingForConcern = useCallback(
+    (concernId: string) => obsControlsRef.current?.onAddFinding(concernId),
+    []
+  )
+  const onReferenceChange = useCallback((reference: string) => {
+    referenceTextRef.current = reference
+  }, [])
+
   // The page's body in two halves: the job itself, and the sidebar beside it.
   const jobProps: WorkOrderJobProps = {
     formState,
@@ -590,21 +697,19 @@ export function ServicePageClient({
     defaultMarkupPercent,
     markupAppliesToInventory,
     hasPresets: laborPresets.length > 0,
-    onOpenPresets: () => formState.setShowPresetPicker(true),
-    onScanBarcode: () => formState.setShowBarcodeScanner(true),
+    onOpenPresets,
+    onScanBarcode,
     aiEnabled,
     vehicleId,
     findings,
-    onAddFinding: () => obsControlsRef.current?.onAddFinding(),
-    onEditFinding: (f) => obsControlsRef.current?.onEditFinding(f),
+    onAddFinding,
+    onEditFinding,
     openObservationsCount: otherObsCount,
-    onShowExistingObservations: () => obsControlsRef.current?.onShowExistingObservations(),
+    onShowExistingObservations,
     jobClock,
     locked: lockState.locked,
     payCode,
-    onReferenceChange: (reference) => {
-      referenceTextRef.current = reference
-    },
+    onReferenceChange,
   }
 
   const sidebarProps: WorkOrderSidebarProps = {
@@ -648,9 +753,24 @@ export function ServicePageClient({
     unsavedMessage: tTaxOffer('saveFirst'),
   })
 
+  const { concerns } = formState
+  const savedConcerns = useMemo(
+    () =>
+      concerns.filter(
+        (c): c is { id: string; description: string; sortOrder: number } =>
+          Boolean(c.id) && Boolean(c.description.trim())
+      ),
+    [concerns]
+  )
+
+  // One object while nothing in it changes: every part and labour line reads
+  // it, and a new one on each render drew them all again.
+  const untaxedDocument = formState.taxRate <= 0
+  const lineTaxValue = useMemo(() => ({ ...lineTax, untaxedDocument }), [lineTax, untaxedDocument])
+
   return (
     <ShopFeeProvider value={shopFee}>
-      <LineTaxProvider value={{ ...lineTax, untaxedDocument: formState.taxRate <= 0 }}>
+      <LineTaxProvider value={lineTaxValue}>
         <WorkshopTaxOfferProvider value={taxOfferValue}>
           <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
             <ModernHero
@@ -658,28 +778,9 @@ export function ServicePageClient({
               status={formState.status}
               paymentStatus={formState.paymentStatus}
               warranty={formState.warranty}
-              actions={
-                <>
-                  <PresenceChips kind="serviceRecord" id={record.id} className="mr-1" />
-                  <ServiceHeaderActions showSave {...headerActionProps} />
-                </>
-              }
+              actions={heroActions}
               title={title}
-              onTitleChange={(next) => {
-                setTitle(next)
-                // Saved the moment the field is left, on its own, not with the
-                // form's autosave five seconds later: a rename followed by the
-                // back arrow inside those seconds was lost. Only a refused save
-                // marks the form dirty, so the ordinary path can try again.
-                void updateServiceRecordTitle(record.id, next).then((result) => {
-                  if (result.success) {
-                    formState.flashSaved()
-                  } else {
-                    toast.error(result.error || t('page.failedUpdate'))
-                    formState.markDirty()
-                  }
-                })
-              }}
+              onTitleChange={onTitleChange}
               type={record.vehicle ? formState.type : undefined}
               onTypeChange={formState.dirtySetType}
               locked={lockState.locked}
@@ -721,10 +822,7 @@ export function ServicePageClient({
                 serviceRecordId={record.id}
                 locked={lockState.locked}
                 // Saved concerns only, as for findings.
-                concerns={formState.concerns.filter(
-                  (c): c is { id: string; description: string; sortOrder: number } =>
-                    Boolean(c.id) && Boolean(c.description.trim())
-                )}
+                concerns={savedConcerns}
               >
                 <ModernDetails
                   {...jobProps}
@@ -755,16 +853,14 @@ export function ServicePageClient({
                     // A link with `?tab=` opens that tab here.
                     initialTab:
                       isFileTab || requestedTab === 'statusReports' ? requestedTab : undefined,
-                    statusReports: { count: statusReports.length, list: statusReportList },
+                    statusReports: statusReportsSection,
                   }}
                   onPreviewInvoice={previewInvoice}
                   onSendToCustomer={shareInvoice}
                   title={title}
                   aiTranscription={aiTranscription}
                   dictationMode={dictationMode}
-                  onAddFindingForConcern={(concernId) =>
-                    obsControlsRef.current?.onAddFinding(concernId)
-                  }
+                  onAddFindingForConcern={onAddFindingForConcern}
                   scrollToFiles={isFileTab || requestedTab === 'statusReports'}
                 />
               </MaybeFaultCodes>
@@ -777,10 +873,7 @@ export function ServicePageClient({
                   addingObservations={addingObservations}
                   // Saved concerns only: a row still being typed has no id yet, so
                   // there is nothing a finding could point at.
-                  concerns={formState.concerns.filter(
-                    (c): c is { id: string; description: string; sortOrder: number } =>
-                      Boolean(c.id) && Boolean(c.description.trim())
-                  )}
+                  concerns={savedConcerns}
                   onControlsReady={(c) => {
                     obsControlsRef.current = c
                   }}

+ 122 - 66
src/features/vehicles/Components/service-page/modern/ModernDetails.tsx

@@ -1,12 +1,22 @@
 'use client'
 
-import { useEffect, useMemo, useRef, useState, type ComponentProps, type ReactNode } from 'react'
+import {
+  memo,
+  useCallback,
+  useEffect,
+  useMemo,
+  useRef,
+  useState,
+  type ComponentProps,
+  type ReactNode,
+} from 'react'
 import { flushSync } from 'react-dom'
 import { useRouter } from 'next/navigation'
 import { useTranslations } from 'next-intl'
 import { Receipt } from 'lucide-react'
 import { AppCard } from '@/components/app-card'
 import { useConfirm } from '@/components/confirm-dialog'
+import { useStableCallback } from '@/hooks/use-stable-callback'
 import { Badge } from '@/components/ui/badge'
 import { SharedLinkCard } from '@/components/shared-link-card'
 import { CustomFieldsForm } from '@/features/custom-fields/Components/CustomFieldsForm'
@@ -23,25 +33,50 @@ import { revealRequiredMeters } from '@/features/meters/Lib/requiredMetersReveal
 import { PaymentsSection } from '../../service-detail/PaymentsSection'
 import { ServiceFindingsSection } from '../../service-detail/ServiceFindingsSection'
 import { paymentStatusColors, paymentStatusLabels } from '../../service-detail/types'
-import { ConcernsSection } from '../../service-edit/ConcernsSection'
-import { InvoiceDetailsSection } from '../../service-edit/InvoiceDetailsSection'
-import { LaborEditor } from '../../service-edit/LaborEditor'
+import { ConcernsSection as ConcernsSectionBase } from '../../service-edit/ConcernsSection'
+import { InvoiceDetailsSection as InvoiceDetailsSectionBase } from '../../service-edit/InvoiceDetailsSection'
+import { LaborEditor as LaborEditorBase } from '../../service-edit/LaborEditor'
 import { servicePartFromFluid } from '../../labor-guide/guide-lines'
-import { NotesSection } from '../../service-edit/NotesSection'
-import { PartsEditor } from '../../service-edit/PartsEditor'
-import { ScheduleTimesSection } from '../../service-edit/ScheduleTimesSection'
+import { NotesSection as NotesSectionBase } from '../../service-edit/NotesSection'
+import { PartsEditor as PartsEditorBase } from '../../service-edit/PartsEditor'
+import { ScheduleTimesSection as ScheduleTimesSectionBase } from '../../service-edit/ScheduleTimesSection'
 import { TotalsSection } from '../../service-edit/TotalsSection'
-import { VideoCallSection } from '../VideoCallSection'
-import { WarrantySection } from '../WarrantySection'
+import { VideoCallSection as VideoCallSectionBase } from '../VideoCallSection'
+import { WarrantySection as WarrantySectionBase } from '../WarrantySection'
 import type { WorkOrderJobProps, WorkOrderSidebarProps } from './details-props'
-import { ActivityCard } from './ActivityCard'
-import { FilesMediaCard } from './FilesMediaCard'
-import { JobFactsCard } from './JobFactsCard'
+import { ActivityCard as ActivityCardBase } from './ActivityCard'
+import { FilesMediaCard as FilesMediaCardBase } from './FilesMediaCard'
+import { JobFactsCard as JobFactsCardBase } from './JobFactsCard'
 import { MoneyBar, MoneyLine } from './MoneyBar'
 import type { WorkOrderStatusOption } from '@/features/work-order-statuses/Lib/stages'
-import { StatusStepper } from './StatusStepper'
+import { StatusStepper as StatusStepperBase } from './StatusStepper'
 import { vehicleName } from '@/lib/vehicle-name'
 
+/**
+ * The sections of the page, memoized. The form's state lives at the top of
+ * the page, so every keystroke in a line renders this component; without
+ * these, it also rendered every card on the page, the ones that show nothing
+ * of what was typed included. Each is drawn again only when something it is
+ * handed changes, which is why the handlers below keep their identity.
+ */
+const StatusStepper = memo(StatusStepperBase)
+const JobFactsCard = memo(JobFactsCardBase)
+const ConcernsSection = memo(ConcernsSectionBase)
+const LaborEditor = memo(LaborEditorBase)
+const PartsEditor = memo(PartsEditorBase)
+const FilesMediaCard = memo(FilesMediaCardBase)
+const NotesSection = memo(NotesSectionBase)
+const ScheduleTimesSection = memo(ScheduleTimesSectionBase)
+const InvoiceDetailsSection = memo(InvoiceDetailsSectionBase)
+const WarrantySection = memo(WarrantySectionBase)
+const VideoCallSection = memo(VideoCallSectionBase)
+const ActivityCard = memo(ActivityCardBase)
+const CustomFieldsFormMemo = memo(CustomFieldsForm)
+const JobClockSectionMemo = memo(JobClockSection)
+
+const NO_FINDINGS: NonNullable<WorkOrderJobProps['findings']> = []
+const NO_NOTIFICATIONS: NonNullable<WorkOrderSidebarProps['notificationHistory']> = []
+
 export interface ModernDetailsProps
   extends WorkOrderJobProps,
     Omit<WorkOrderSidebarProps, keyof WorkOrderJobProps> {
@@ -80,7 +115,7 @@ export interface ModernDetailsProps
   dictationMode?: 'ai' | 'choice'
   /** Opens the finding form already pointed at one concern. */
   onAddFindingForConcern?: (concernId: string) => void
-  files: Omit<ComponentProps<typeof FilesMediaCard>, 'serviceRecordId' | 'customerId'>
+  files: Omit<ComponentProps<typeof FilesMediaCardBase>, 'serviceRecordId' | 'customerId'>
   onPreviewInvoice: () => void
   onSendToCustomer: () => void
 }
@@ -131,11 +166,11 @@ export function ModernDetails(props: ModernDetailsProps) {
     currencyCode,
     unitSystem = 'metric',
     vehicleId,
-    findings = [],
+    findings = NO_FINDINGS,
     tireSet = null,
     tireHotelEnabled = false,
     tireThresholds,
-    notificationHistory = [],
+    notificationHistory = NO_NOTIFICATIONS,
   } = props
   const t = useTranslations('service')
   const tClock = useTranslations('timeTracking.job')
@@ -243,6 +278,43 @@ export function ModernDetails(props: ModernDetailsProps) {
     }
   }
 
+  // The same handlers on every render, for the memoized sections: each runs
+  // the version from the latest render, so nothing it reads is stale.
+  const onStepperChange = useStableCallback(
+    (next: string, custom: WorkOrderStatusOption | null) => void changeStatus(next, custom)
+  )
+  const { flashSaved, dirtySetPartItems, dirtySetLaborItems, setShowInventoryPicker } = formState
+  const onReferenceSaved = useCallback(() => {
+    flashSaved()
+    router.refresh()
+  }, [flashSaved, router])
+  const onCustomerAdded = useCallback(() => router.refresh(), [router])
+  const onAddGuidePart = useCallback(
+    (line: Parameters<typeof servicePartFromFluid>[0]) =>
+      dirtySetPartItems((prev) => [servicePartFromFluid(line), ...prev]),
+    [dirtySetPartItems]
+  )
+  const onOpenInventory = useCallback(() => setShowInventoryPicker(true), [setShowInventoryPicker])
+  const clockLaborDescription = tClock('laborDescription')
+  const { defaultLaborRate } = props
+  const addClockLabor = useCallback(
+    (hours: number) =>
+      dirtySetLaborItems((prev) => [
+        ...prev,
+        {
+          description: clockLaborDescription,
+          hours,
+          rate: defaultLaborRate,
+          total: Math.round(hours * defaultLaborRate * 100) / 100,
+          pricingType: 'hourly' as const,
+        },
+      ]),
+    [dirtySetLaborItems, clockLaborDescription, defaultLaborRate]
+  )
+  const onTogglePaid = useStableCallback(actions.handleTogglePaid)
+  const helperIds = useMemo(() => record.helpers?.map((h) => h.technicianId), [record.helpers])
+  const vehicleLabel = record.vehicle ? `${vehicleName(record.vehicle)}` : undefined
+
   // Internal notes on a locked invoice. The form's save is refused there, but
   // these notes are never printed or shared, so they are saved on their own,
   // a moment after the typing stops. Unlocked, they go with the form as always.
@@ -253,22 +325,21 @@ export function ModernDetails(props: ModernDetailsProps) {
     if (result.success) formState.flashSaved()
     else toast.error(t('page.failedUpdate'))
   }
-  const onNotesChange = (
-    field: 'invoiceNotes' | 'diagnosticNotes' | 'description',
-    value: string
-  ) => {
-    // Keeps the form's copy current; it marks nothing dirty while locked.
-    formState.handleNotesChange(field, value)
-    if (!locked || field !== 'diagnosticNotes') return
-    pendingNotes.current = value
-    if (notesTimer.current) clearTimeout(notesTimer.current)
-    notesTimer.current = setTimeout(() => {
-      notesTimer.current = null
-      const html = pendingNotes.current
-      pendingNotes.current = null
-      if (html !== null) void saveInternalNotes(html)
-    }, 800)
-  }
+  const onNotesChange = useStableCallback(
+    (field: 'invoiceNotes' | 'diagnosticNotes' | 'description', value: string) => {
+      // Keeps the form's copy current; it marks nothing dirty while locked.
+      formState.handleNotesChange(field, value)
+      if (!locked || field !== 'diagnosticNotes') return
+      pendingNotes.current = value
+      if (notesTimer.current) clearTimeout(notesTimer.current)
+      notesTimer.current = setTimeout(() => {
+        notesTimer.current = null
+        const html = pendingNotes.current
+        pendingNotes.current = null
+        if (html !== null) void saveInternalNotes(html)
+      }, 800)
+    }
+  )
   // Leaving the page mid-sentence still saves what was typed.
   useEffect(() => {
     const recordId = record.id
@@ -282,10 +353,14 @@ export function ModernDetails(props: ModernDetailsProps) {
     if (scrollToFiles) document.getElementById('files-media')?.scrollIntoView()
   }, [scrollToFiles])
 
-  const answeredCounts = findings.reduce<Record<string, number>>((counts, finding) => {
-    if (finding.concernId) counts[finding.concernId] = (counts[finding.concernId] ?? 0) + 1
-    return counts
-  }, {})
+  const answeredCounts = useMemo(
+    () =>
+      findings.reduce<Record<string, number>>((counts, finding) => {
+        if (finding.concernId) counts[finding.concernId] = (counts[finding.concernId] ?? 0) + 1
+        return counts
+      }, {}),
+    [findings]
+  )
 
   const storeTires =
     tireHotelEnabled && record.vehicle ? (
@@ -343,7 +418,7 @@ export function ModernDetails(props: ModernDetailsProps) {
               customStatus={customStatus}
               options={props.workOrderStatuses}
               canAddStatus={props.canAddStatus}
-              onChange={(next, custom) => void changeStatus(next, custom)}
+              onChange={onStepperChange}
             />
 
             {/* The side column gives way before the job does: the parts and labour
@@ -366,15 +441,12 @@ export function ModernDetails(props: ModernDetailsProps) {
                   techName={formState.techName}
                   initialVehicle={props.initialVehicle}
                   onReferenceChange={props.onReferenceChange}
-                  onReferenceSaved={() => {
-                    formState.flashSaved()
-                    router.refresh()
-                  }}
+                  onReferenceSaved={onReferenceSaved}
                   distanceUnit={unitSystem === 'metric' ? 'km' : 'mi'}
                   confirmedReading={formState.confirmedReading}
                   onConfirmReading={formState.confirmReading}
                   canSetCustomer={props.canSetCustomer}
-                  onCustomerAdded={() => router.refresh()}
+                  onCustomerAdded={onCustomerAdded}
                 />
 
                 <Lockable locked={locked}>
@@ -424,11 +496,9 @@ export function ModernDetails(props: ModernDetailsProps) {
                     openObservationsCount={props.openObservationsCount}
                     onShowExistingObservations={props.onShowExistingObservations}
                     vehicleId={record.vehicle?.id ?? null}
-                    vehicleLabel={record.vehicle ? `${vehicleName(record.vehicle)}` : undefined}
+                    vehicleLabel={vehicleLabel}
                     guideStock={guideStock}
-                    onAddGuidePart={(line) =>
-                      formState.dirtySetPartItems((prev) => [servicePartFromFluid(line), ...prev])
-                    }
+                    onAddGuidePart={onAddGuidePart}
                   />
 
                   <PartsEditor
@@ -439,7 +509,7 @@ export function ModernDetails(props: ModernDetailsProps) {
                     currencyCode={currencyCode}
                     hasInventory={props.inventoryParts.length > 0}
                     inventoryParts={props.inventoryParts}
-                    onOpenInventory={() => formState.setShowInventoryPicker(true)}
+                    onOpenInventory={onOpenInventory}
                     onScanBarcode={props.onScanBarcode}
                     defaultMarkupPercent={props.defaultMarkupPercent}
                     markupAppliesToInventory={props.markupAppliesToInventory}
@@ -480,7 +550,7 @@ export function ModernDetails(props: ModernDetailsProps) {
                   initialStartDateTime={formState.initialData.startDateTime}
                   initialEndDateTime={formState.initialData.endDateTime}
                   initialTechnicianId={record.technicianId}
-                  initialHelperIds={record.helpers?.map((h) => h.technicianId)}
+                  initialHelperIds={helperIds}
                   initialWorkBayId={record.workBayId}
                   initialPromisedAt={
                     record.promisedAt ? new Date(record.promisedAt).toISOString() : null
@@ -492,24 +562,10 @@ export function ModernDetails(props: ModernDetailsProps) {
                     and the parts: it says how the work is going, and the two
                     cards it sat between are the invoice being built. "Add as
                     labour" still puts its line in the labour card. */}
-                <JobClockSection
+                <JobClockSectionMemo
                   serviceRecordId={record.id}
                   initial={props.jobClock}
-                  onAddLabor={
-                    locked
-                      ? undefined
-                      : (hours) =>
-                          formState.dirtySetLaborItems((prev) => [
-                            ...prev,
-                            {
-                              description: tClock('laborDescription'),
-                              hours,
-                              rate: props.defaultLaborRate,
-                              total: Math.round(hours * props.defaultLaborRate * 100) / 100,
-                              pricingType: 'hourly' as const,
-                            },
-                          ])
-                  }
+                  onAddLabor={locked ? undefined : addClockLabor}
                 />
 
                 <AppCard
@@ -537,7 +593,7 @@ export function ModernDetails(props: ModernDetailsProps) {
                         setStatus={formState.dirtySetStatus}
                         onDirty={formState.markDirty}
                         paymentStatus={formState.paymentStatus}
-                        onTogglePaid={actions.handleTogglePaid}
+                        onTogglePaid={onTogglePaid}
                         designOptions={props.designOptions}
                         designId={record.designId ?? null}
                         designFollowsName={props.designFollowsName}
@@ -629,7 +685,7 @@ export function ModernDetails(props: ModernDetailsProps) {
                 )}
 
                 <Lockable locked={locked}>
-                  <CustomFieldsForm
+                  <CustomFieldsFormMemo
                     entityId={record.id}
                     entityType="service_record"
                     locked={locked}

+ 24 - 0
src/hooks/use-stable-callback.ts

@@ -0,0 +1,24 @@
+import { useCallback, useInsertionEffect, useRef } from 'react'
+
+/**
+ * A function that never changes identity and always runs the version of
+ * `callback` from the render that is on screen.
+ *
+ * For a handler handed to a memoized child: an inline arrow is a new function
+ * on every render, which makes the child render again although nothing it
+ * shows has changed. Only for functions called from events, timers and
+ * effects, never while rendering.
+ */
+export function useStableCallback<Args extends unknown[], Result>(
+  callback: (...args: Args) => Result
+): (...args: Args) => Result {
+  const latest = useRef(callback)
+  // Swapped in when the render commits, before any other effect runs, never
+  // while rendering: a render React starts and then abandons (a transition
+  // that suspends or is interrupted) must not leave its handlers behind for
+  // the page that is still showing.
+  useInsertionEffect(() => {
+    latest.current = callback
+  })
+  return useCallback((...args: Args) => latest.current(...args), [])
+}