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

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'
 '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 { useRouter } from 'next/navigation'
 import { useTranslations } from 'next-intl'
 import { useTranslations } from 'next-intl'
 import { History, RefreshCw } from 'lucide-react'
 import { History, RefreshCw } from 'lucide-react'
@@ -64,14 +72,20 @@ export function FaultCodesJobProvider({
 }) {
 }) {
   const [entryOpen, setEntryOpen] = useState(false)
   const [entryOpen, setEntryOpen] = useState(false)
   const [sheetCode, setSheetCode] = useState<string | null>(null)
   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 (
   return (
     <Ctx.Provider value={value}>
     <Ctx.Provider value={value}>
       {children}
       {children}

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

@@ -80,12 +80,22 @@ export function PaymentsSection({
   useEffect(() => {
   useEffect(() => {
     if (openFormSignal === 0) return
     if (openFormSignal === 0) return
     setShowForm(true)
     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(() => {
     requestAnimationFrame(() => {
       sectionRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' })
       sectionRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' })
       formRef.current?.querySelector<HTMLInputElement>('[name="paymentAmount"]')?.focus()
       formRef.current?.querySelector<HTMLInputElement>('[name="paymentAmount"]')?.focus()
     })
     })
-  }, [openFormSignal])
+  }, [showForm, openFormSignal])
 
 
   const handleSubmit = async () => {
   const handleSubmit = async () => {
     if (!formRef.current) return
     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 { LineTaxToggle } from '@/features/settings/Components/LineTaxToggle'
 import { useLineTax } from '@/features/settings/Components/LineTaxContext'
 import { useLineTax } from '@/features/settings/Components/LineTaxContext'
 import { laborTaxable } from '@/lib/taxable-lines'
 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 { Button } from '@/components/ui/button'
 import { Input } from '@/components/ui/input'
 import { Input } from '@/components/ui/input'
 import { Textarea } from '@/components/ui/textarea'
 import { Textarea } from '@/components/ui/textarea'
@@ -73,7 +73,17 @@ interface LaborEditorProps {
   guideStock?: LaborGuideStock
   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,
   id,
   labor,
   labor,
   index,
   index,
@@ -82,22 +92,23 @@ function SortableLaborRow({
   onToggleTax,
   onToggleTax,
   currencyCode,
   currencyCode,
   rateLabel,
   rateLabel,
-  t,
   dragEnabled,
   dragEnabled,
 }: {
 }: {
   id: string
   id: string
   labor: ServiceLaborInput
   labor: ServiceLaborInput
   index: number
   index: number
   updateLabor: (index: number, field: keyof ServiceLaborInput, value: string | number) => void
   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. */
   /** Flips whether the job's tax is charged on this line. */
-  onToggleTax: () => void
+  onToggleTax: (index: number) => void
   currencyCode: string
   currencyCode: string
   /** Pre-formatted "Rate (kr/hr)" header, which needs the currency symbol. */
   /** Pre-formatted "Rate (kr/hr)" header, which needs the currency symbol. */
   rateLabel: string
   rateLabel: string
-  t: (key: string) => string
   dragEnabled: boolean
   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 formatCurrency = useFormatCurrency()
   const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
   const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
     id,
     id,
@@ -163,7 +174,10 @@ function SortableLaborRow({
               {isService ? t('serviceTag') : t('hourlyTag')}
               {isService ? t('serviceTag') : t('hourlyTag')}
             </button>
             </button>
           )}
           )}
-          <LineTaxToggle taxable={laborTaxable(labor, applies)} onToggle={onToggleTax} />
+          <LineTaxToggle
+            taxable={laborTaxable(labor, applies)}
+            onToggle={() => onToggleTax(index)}
+          />
         </div>
         </div>
         <FieldRow label={isService || isFee ? t('qty') : t('hours')}>
         <FieldRow label={isService || isFee ? t('qty') : t('hours')}>
           <Input
           <Input
@@ -198,7 +212,7 @@ function SortableLaborRow({
             variant="ghost"
             variant="ghost"
             size="icon"
             size="icon"
             className="h-9 w-9 shrink-0 text-muted-foreground hover:text-destructive"
             className="h-9 w-9 shrink-0 text-muted-foreground hover:text-destructive"
-            onClick={onDelete}
+            onClick={() => onDelete(index)}
             aria-label={t('deleteRow')}
             aria-label={t('deleteRow')}
           >
           >
             <Trash2 className="h-4 w-4" />
             <Trash2 className="h-4 w-4" />
@@ -207,7 +221,7 @@ function SortableLaborRow({
       </div>
       </div>
     </div>
     </div>
   )
   )
-}
+})
 
 
 export function LaborEditor({
 export function LaborEditor({
   laborItems,
   laborItems,
@@ -247,8 +261,8 @@ export function LaborEditor({
   }
   }
 
 
   const sensors = useSensors(
   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(
   const handleDragEnd = useCallback(
@@ -424,11 +438,10 @@ export function LaborEditor({
                     labor={labor}
                     labor={labor}
                     index={i}
                     index={i}
                     updateLabor={updateLabor}
                     updateLabor={updateLabor}
-                    onDelete={() => deleteLabor(i)}
-                    onToggleTax={() => toggleLaborTax(i)}
+                    onDelete={deleteLabor}
+                    onToggleTax={toggleLaborTax}
                     currencyCode={currencyCode}
                     currencyCode={currencyCode}
                     rateLabel={t('rate', { currency: cs })}
                     rateLabel={t('rate', { currency: cs })}
-                    t={t}
                     dragEnabled
                     dragEnabled
                   />
                   />
                 ))}
                 ))}
@@ -442,11 +455,10 @@ export function LaborEditor({
                 labor={labor}
                 labor={labor}
                 index={i}
                 index={i}
                 updateLabor={updateLabor}
                 updateLabor={updateLabor}
-                onDelete={() => deleteLabor(i)}
-                onToggleTax={() => toggleLaborTax(i)}
+                onDelete={deleteLabor}
+                onToggleTax={toggleLaborTax}
                 currencyCode={currencyCode}
                 currencyCode={currencyCode}
                 rateLabel={t('rate', { currency: cs })}
                 rateLabel={t('rate', { currency: cs })}
-                t={t}
                 dragEnabled={false}
                 dragEnabled={false}
               />
               />
             ))
             ))

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

@@ -1,6 +1,6 @@
 'use client'
 '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 { Button } from '@/components/ui/button'
 import { Input } from '@/components/ui/input'
 import { Input } from '@/components/ui/input'
 import { Textarea } from '@/components/ui/textarea'
 import { Textarea } from '@/components/ui/textarea'
@@ -69,7 +69,19 @@ interface PartsEditorProps {
   markupAppliesToInventory?: boolean
   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,
   id,
   part,
   part,
   index,
   index,
@@ -77,7 +89,6 @@ function SortablePartRow({
   onDelete,
   onDelete,
   onToggleTax,
   onToggleTax,
   currencyCode,
   currencyCode,
-  t,
   dragEnabled,
   dragEnabled,
   inventoryParts,
   inventoryParts,
   onSelectSuggestion,
   onSelectSuggestion,
@@ -96,17 +107,19 @@ function SortablePartRow({
     value: string | number,
     value: string | number,
     options?: { commit?: boolean }
     options?: { commit?: boolean }
   ) => void
   ) => void
-  onDelete: () => void
+  onDelete: (index: number) => void
   /** Flips whether the job's tax is charged on this line. */
   /** Flips whether the job's tax is charged on this line. */
-  onToggleTax: () => void
+  onToggleTax: (index: number) => void
   currencyCode: string
   currencyCode: string
   inventoryParts: PartSuggestion[]
   inventoryParts: PartSuggestion[]
   onSelectSuggestion: (index: number, part: PartSuggestion) => void
   onSelectSuggestion: (index: number, part: PartSuggestion) => void
   defaultMarkupPercent: number
   defaultMarkupPercent: number
   markupAppliesToInventory: boolean
   markupAppliesToInventory: boolean
-  t: (key: string) => string
   dragEnabled: boolean
   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 formatCurrency = useFormatCurrency()
   const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
   const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
     id,
     id,
@@ -184,7 +197,10 @@ function SortablePartRow({
                 onSelect={(picked) => onSelectSuggestion(index, picked)}
                 onSelect={(picked) => onSelectSuggestion(index, picked)}
               />
               />
             </div>
             </div>
-            <LineTaxToggle taxable={partTaxable(part, applies)} onToggle={onToggleTax} />
+            <LineTaxToggle
+              taxable={partTaxable(part, applies)}
+              onToggle={() => onToggleTax(index)}
+            />
           </div>
           </div>
         </FieldRow>
         </FieldRow>
         <FieldRow label={t('qty')}>
         <FieldRow label={t('qty')}>
@@ -256,7 +272,7 @@ function SortablePartRow({
             variant="ghost"
             variant="ghost"
             size="icon"
             size="icon"
             className="h-9 w-9 shrink-0 text-muted-foreground hover:text-destructive"
             className="h-9 w-9 shrink-0 text-muted-foreground hover:text-destructive"
-            onClick={onDelete}
+            onClick={() => onDelete(index)}
             aria-label={t('deleteRow')}
             aria-label={t('deleteRow')}
           >
           >
             <Trash2 className="h-4 w-4" />
             <Trash2 className="h-4 w-4" />
@@ -265,7 +281,7 @@ function SortablePartRow({
       </div>
       </div>
     </div>
     </div>
   )
   )
-}
+})
 
 
 export function PartsEditor({
 export function PartsEditor({
   partItems,
   partItems,
@@ -274,7 +290,7 @@ export function PartsEditor({
   partsSubtotal,
   partsSubtotal,
   currencyCode,
   currencyCode,
   hasInventory,
   hasInventory,
-  inventoryParts = [],
+  inventoryParts = NO_INVENTORY,
   onOpenInventory,
   onOpenInventory,
   onScanBarcode,
   onScanBarcode,
   defaultMarkupPercent = 0,
   defaultMarkupPercent = 0,
@@ -343,8 +359,8 @@ export function PartsEditor({
   }
   }
 
 
   const sensors = useSensors(
   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(
   const handleDragEnd = useCallback(
@@ -471,10 +487,9 @@ export function PartsEditor({
                     part={part}
                     part={part}
                     index={i}
                     index={i}
                     updatePart={updatePart}
                     updatePart={updatePart}
-                    onDelete={() => deletePart(i)}
-                    onToggleTax={() => togglePartTax(i)}
+                    onDelete={deletePart}
+                    onToggleTax={togglePartTax}
                     currencyCode={currencyCode}
                     currencyCode={currencyCode}
-                    t={t}
                     dragEnabled
                     dragEnabled
                     inventoryParts={inventoryParts}
                     inventoryParts={inventoryParts}
                     onSelectSuggestion={handleSelectSuggestion}
                     onSelectSuggestion={handleSelectSuggestion}
@@ -493,10 +508,9 @@ export function PartsEditor({
                 part={part}
                 part={part}
                 index={i}
                 index={i}
                 updatePart={updatePart}
                 updatePart={updatePart}
-                onDelete={() => deletePart(i)}
-                onToggleTax={() => togglePartTax(i)}
+                onDelete={deletePart}
+                onToggleTax={togglePartTax}
                 currencyCode={currencyCode}
                 currencyCode={currencyCode}
-                t={t}
                 dragEnabled={false}
                 dragEnabled={false}
                 inventoryParts={inventoryParts}
                 inventoryParts={inventoryParts}
                 onSelectSuggestion={handleSelectSuggestion}
                 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 { InvoiceDesignMenu } from './InvoiceDesignMenu'
 import { PayCodeButton } from './PayCodeButton'
 import { PayCodeButton } from './PayCodeButton'
 import type { WorkOrderStatusOption } from '@/features/work-order-statuses/Lib/stages'
 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 { useRouter } from 'next/navigation'
 import { sendInvoiceEmail } from '@/features/email/Actions/emailActions'
 import { sendInvoiceEmail } from '@/features/email/Actions/emailActions'
 import {
 import {
@@ -31,6 +31,7 @@ import { InventoryPickerDialog } from '../service-edit/InventoryPickerDialog'
 import { BarcodeScannerDialog } from '@/components/barcode-scanner-dialog'
 import { BarcodeScannerDialog } from '@/components/barcode-scanner-dialog'
 import { useHardwareScanner } from '@/hooks/use-hardware-scanner'
 import { useHardwareScanner } from '@/hooks/use-hardware-scanner'
 import { useSaveShortcut } from '@/hooks/use-save-shortcut'
 import { useSaveShortcut } from '@/hooks/use-save-shortcut'
+import { useStableCallback } from '@/hooks/use-stable-callback'
 import { lookupPartByBarcode } from '@/features/inventory/Actions/lookupPartByBarcode'
 import { lookupPartByBarcode } from '@/features/inventory/Actions/lookupPartByBarcode'
 import { toast } from 'sonner'
 import { toast } from 'sonner'
 import { Button } from '@/components/ui/button'
 import { Button } from '@/components/ui/button'
@@ -69,7 +70,7 @@ import { PresenceChips } from '@/features/realtime/Components/PresenceChips'
 import { ModernDetails } from './modern/ModernDetails'
 import { ModernDetails } from './modern/ModernDetails'
 import { useCustomerReferenceEnabled } from '@/components/customer-reference-context'
 import { useCustomerReferenceEnabled } from '@/components/customer-reference-context'
 import { referenceMissing } from '@/features/customer-reference/Lib/reference'
 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 { revealRequiredMeters } from '@/features/meters/Lib/requiredMetersReveal'
 import type { WorkOrderJobProps, WorkOrderSidebarProps } from './modern/details-props'
 import type { WorkOrderJobProps, WorkOrderSidebarProps } from './modern/details-props'
 import { lineTotal, resolvePartPrice } from '@/features/inventory/Lib/partPricing'
 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'
 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({
 export function ServicePageClient({
   record,
   record,
   vehicleId,
   vehicleId,
@@ -504,62 +512,139 @@ export function ServicePageClient({
     actions.setShowShareDialog(true)
     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,
   // 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
   // drawn wherever a payment is taken: beside "Record payment" and on the
@@ -575,6 +660,28 @@ export function ServicePageClient({
     />
     />
   ) : null
   ) : 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.
   // The page's body in two halves: the job itself, and the sidebar beside it.
   const jobProps: WorkOrderJobProps = {
   const jobProps: WorkOrderJobProps = {
     formState,
     formState,
@@ -590,21 +697,19 @@ export function ServicePageClient({
     defaultMarkupPercent,
     defaultMarkupPercent,
     markupAppliesToInventory,
     markupAppliesToInventory,
     hasPresets: laborPresets.length > 0,
     hasPresets: laborPresets.length > 0,
-    onOpenPresets: () => formState.setShowPresetPicker(true),
-    onScanBarcode: () => formState.setShowBarcodeScanner(true),
+    onOpenPresets,
+    onScanBarcode,
     aiEnabled,
     aiEnabled,
     vehicleId,
     vehicleId,
     findings,
     findings,
-    onAddFinding: () => obsControlsRef.current?.onAddFinding(),
-    onEditFinding: (f) => obsControlsRef.current?.onEditFinding(f),
+    onAddFinding,
+    onEditFinding,
     openObservationsCount: otherObsCount,
     openObservationsCount: otherObsCount,
-    onShowExistingObservations: () => obsControlsRef.current?.onShowExistingObservations(),
+    onShowExistingObservations,
     jobClock,
     jobClock,
     locked: lockState.locked,
     locked: lockState.locked,
     payCode,
     payCode,
-    onReferenceChange: (reference) => {
-      referenceTextRef.current = reference
-    },
+    onReferenceChange,
   }
   }
 
 
   const sidebarProps: WorkOrderSidebarProps = {
   const sidebarProps: WorkOrderSidebarProps = {
@@ -648,9 +753,24 @@ export function ServicePageClient({
     unsavedMessage: tTaxOffer('saveFirst'),
     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 (
   return (
     <ShopFeeProvider value={shopFee}>
     <ShopFeeProvider value={shopFee}>
-      <LineTaxProvider value={{ ...lineTax, untaxedDocument: formState.taxRate <= 0 }}>
+      <LineTaxProvider value={lineTaxValue}>
         <WorkshopTaxOfferProvider value={taxOfferValue}>
         <WorkshopTaxOfferProvider value={taxOfferValue}>
           <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
           <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
             <ModernHero
             <ModernHero
@@ -658,28 +778,9 @@ export function ServicePageClient({
               status={formState.status}
               status={formState.status}
               paymentStatus={formState.paymentStatus}
               paymentStatus={formState.paymentStatus}
               warranty={formState.warranty}
               warranty={formState.warranty}
-              actions={
-                <>
-                  <PresenceChips kind="serviceRecord" id={record.id} className="mr-1" />
-                  <ServiceHeaderActions showSave {...headerActionProps} />
-                </>
-              }
+              actions={heroActions}
               title={title}
               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}
               type={record.vehicle ? formState.type : undefined}
               onTypeChange={formState.dirtySetType}
               onTypeChange={formState.dirtySetType}
               locked={lockState.locked}
               locked={lockState.locked}
@@ -721,10 +822,7 @@ export function ServicePageClient({
                 serviceRecordId={record.id}
                 serviceRecordId={record.id}
                 locked={lockState.locked}
                 locked={lockState.locked}
                 // Saved concerns only, as for findings.
                 // 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
                 <ModernDetails
                   {...jobProps}
                   {...jobProps}
@@ -755,16 +853,14 @@ export function ServicePageClient({
                     // A link with `?tab=` opens that tab here.
                     // A link with `?tab=` opens that tab here.
                     initialTab:
                     initialTab:
                       isFileTab || requestedTab === 'statusReports' ? requestedTab : undefined,
                       isFileTab || requestedTab === 'statusReports' ? requestedTab : undefined,
-                    statusReports: { count: statusReports.length, list: statusReportList },
+                    statusReports: statusReportsSection,
                   }}
                   }}
                   onPreviewInvoice={previewInvoice}
                   onPreviewInvoice={previewInvoice}
                   onSendToCustomer={shareInvoice}
                   onSendToCustomer={shareInvoice}
                   title={title}
                   title={title}
                   aiTranscription={aiTranscription}
                   aiTranscription={aiTranscription}
                   dictationMode={dictationMode}
                   dictationMode={dictationMode}
-                  onAddFindingForConcern={(concernId) =>
-                    obsControlsRef.current?.onAddFinding(concernId)
-                  }
+                  onAddFindingForConcern={onAddFindingForConcern}
                   scrollToFiles={isFileTab || requestedTab === 'statusReports'}
                   scrollToFiles={isFileTab || requestedTab === 'statusReports'}
                 />
                 />
               </MaybeFaultCodes>
               </MaybeFaultCodes>
@@ -777,10 +873,7 @@ export function ServicePageClient({
                   addingObservations={addingObservations}
                   addingObservations={addingObservations}
                   // Saved concerns only: a row still being typed has no id yet, so
                   // Saved concerns only: a row still being typed has no id yet, so
                   // there is nothing a finding could point at.
                   // 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) => {
                   onControlsReady={(c) => {
                     obsControlsRef.current = c
                     obsControlsRef.current = c
                   }}
                   }}

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

@@ -1,12 +1,22 @@
 'use client'
 '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 { flushSync } from 'react-dom'
 import { useRouter } from 'next/navigation'
 import { useRouter } from 'next/navigation'
 import { useTranslations } from 'next-intl'
 import { useTranslations } from 'next-intl'
 import { Receipt } from 'lucide-react'
 import { Receipt } from 'lucide-react'
 import { AppCard } from '@/components/app-card'
 import { AppCard } from '@/components/app-card'
 import { useConfirm } from '@/components/confirm-dialog'
 import { useConfirm } from '@/components/confirm-dialog'
+import { useStableCallback } from '@/hooks/use-stable-callback'
 import { Badge } from '@/components/ui/badge'
 import { Badge } from '@/components/ui/badge'
 import { SharedLinkCard } from '@/components/shared-link-card'
 import { SharedLinkCard } from '@/components/shared-link-card'
 import { CustomFieldsForm } from '@/features/custom-fields/Components/CustomFieldsForm'
 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 { PaymentsSection } from '../../service-detail/PaymentsSection'
 import { ServiceFindingsSection } from '../../service-detail/ServiceFindingsSection'
 import { ServiceFindingsSection } from '../../service-detail/ServiceFindingsSection'
 import { paymentStatusColors, paymentStatusLabels } from '../../service-detail/types'
 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 { 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 { 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 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 { MoneyBar, MoneyLine } from './MoneyBar'
 import type { WorkOrderStatusOption } from '@/features/work-order-statuses/Lib/stages'
 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'
 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
 export interface ModernDetailsProps
   extends WorkOrderJobProps,
   extends WorkOrderJobProps,
     Omit<WorkOrderSidebarProps, keyof WorkOrderJobProps> {
     Omit<WorkOrderSidebarProps, keyof WorkOrderJobProps> {
@@ -80,7 +115,7 @@ export interface ModernDetailsProps
   dictationMode?: 'ai' | 'choice'
   dictationMode?: 'ai' | 'choice'
   /** Opens the finding form already pointed at one concern. */
   /** Opens the finding form already pointed at one concern. */
   onAddFindingForConcern?: (concernId: string) => void
   onAddFindingForConcern?: (concernId: string) => void
-  files: Omit<ComponentProps<typeof FilesMediaCard>, 'serviceRecordId' | 'customerId'>
+  files: Omit<ComponentProps<typeof FilesMediaCardBase>, 'serviceRecordId' | 'customerId'>
   onPreviewInvoice: () => void
   onPreviewInvoice: () => void
   onSendToCustomer: () => void
   onSendToCustomer: () => void
 }
 }
@@ -131,11 +166,11 @@ export function ModernDetails(props: ModernDetailsProps) {
     currencyCode,
     currencyCode,
     unitSystem = 'metric',
     unitSystem = 'metric',
     vehicleId,
     vehicleId,
-    findings = [],
+    findings = NO_FINDINGS,
     tireSet = null,
     tireSet = null,
     tireHotelEnabled = false,
     tireHotelEnabled = false,
     tireThresholds,
     tireThresholds,
-    notificationHistory = [],
+    notificationHistory = NO_NOTIFICATIONS,
   } = props
   } = props
   const t = useTranslations('service')
   const t = useTranslations('service')
   const tClock = useTranslations('timeTracking.job')
   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
   // 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,
   // 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.
   // 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()
     if (result.success) formState.flashSaved()
     else toast.error(t('page.failedUpdate'))
     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.
   // Leaving the page mid-sentence still saves what was typed.
   useEffect(() => {
   useEffect(() => {
     const recordId = record.id
     const recordId = record.id
@@ -282,10 +353,14 @@ export function ModernDetails(props: ModernDetailsProps) {
     if (scrollToFiles) document.getElementById('files-media')?.scrollIntoView()
     if (scrollToFiles) document.getElementById('files-media')?.scrollIntoView()
   }, [scrollToFiles])
   }, [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 =
   const storeTires =
     tireHotelEnabled && record.vehicle ? (
     tireHotelEnabled && record.vehicle ? (
@@ -343,7 +418,7 @@ export function ModernDetails(props: ModernDetailsProps) {
               customStatus={customStatus}
               customStatus={customStatus}
               options={props.workOrderStatuses}
               options={props.workOrderStatuses}
               canAddStatus={props.canAddStatus}
               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
             {/* 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}
                   techName={formState.techName}
                   initialVehicle={props.initialVehicle}
                   initialVehicle={props.initialVehicle}
                   onReferenceChange={props.onReferenceChange}
                   onReferenceChange={props.onReferenceChange}
-                  onReferenceSaved={() => {
-                    formState.flashSaved()
-                    router.refresh()
-                  }}
+                  onReferenceSaved={onReferenceSaved}
                   distanceUnit={unitSystem === 'metric' ? 'km' : 'mi'}
                   distanceUnit={unitSystem === 'metric' ? 'km' : 'mi'}
                   confirmedReading={formState.confirmedReading}
                   confirmedReading={formState.confirmedReading}
                   onConfirmReading={formState.confirmReading}
                   onConfirmReading={formState.confirmReading}
                   canSetCustomer={props.canSetCustomer}
                   canSetCustomer={props.canSetCustomer}
-                  onCustomerAdded={() => router.refresh()}
+                  onCustomerAdded={onCustomerAdded}
                 />
                 />
 
 
                 <Lockable locked={locked}>
                 <Lockable locked={locked}>
@@ -424,11 +496,9 @@ export function ModernDetails(props: ModernDetailsProps) {
                     openObservationsCount={props.openObservationsCount}
                     openObservationsCount={props.openObservationsCount}
                     onShowExistingObservations={props.onShowExistingObservations}
                     onShowExistingObservations={props.onShowExistingObservations}
                     vehicleId={record.vehicle?.id ?? null}
                     vehicleId={record.vehicle?.id ?? null}
-                    vehicleLabel={record.vehicle ? `${vehicleName(record.vehicle)}` : undefined}
+                    vehicleLabel={vehicleLabel}
                     guideStock={guideStock}
                     guideStock={guideStock}
-                    onAddGuidePart={(line) =>
-                      formState.dirtySetPartItems((prev) => [servicePartFromFluid(line), ...prev])
-                    }
+                    onAddGuidePart={onAddGuidePart}
                   />
                   />
 
 
                   <PartsEditor
                   <PartsEditor
@@ -439,7 +509,7 @@ export function ModernDetails(props: ModernDetailsProps) {
                     currencyCode={currencyCode}
                     currencyCode={currencyCode}
                     hasInventory={props.inventoryParts.length > 0}
                     hasInventory={props.inventoryParts.length > 0}
                     inventoryParts={props.inventoryParts}
                     inventoryParts={props.inventoryParts}
-                    onOpenInventory={() => formState.setShowInventoryPicker(true)}
+                    onOpenInventory={onOpenInventory}
                     onScanBarcode={props.onScanBarcode}
                     onScanBarcode={props.onScanBarcode}
                     defaultMarkupPercent={props.defaultMarkupPercent}
                     defaultMarkupPercent={props.defaultMarkupPercent}
                     markupAppliesToInventory={props.markupAppliesToInventory}
                     markupAppliesToInventory={props.markupAppliesToInventory}
@@ -480,7 +550,7 @@ export function ModernDetails(props: ModernDetailsProps) {
                   initialStartDateTime={formState.initialData.startDateTime}
                   initialStartDateTime={formState.initialData.startDateTime}
                   initialEndDateTime={formState.initialData.endDateTime}
                   initialEndDateTime={formState.initialData.endDateTime}
                   initialTechnicianId={record.technicianId}
                   initialTechnicianId={record.technicianId}
-                  initialHelperIds={record.helpers?.map((h) => h.technicianId)}
+                  initialHelperIds={helperIds}
                   initialWorkBayId={record.workBayId}
                   initialWorkBayId={record.workBayId}
                   initialPromisedAt={
                   initialPromisedAt={
                     record.promisedAt ? new Date(record.promisedAt).toISOString() : null
                     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
                     and the parts: it says how the work is going, and the two
                     cards it sat between are the invoice being built. "Add as
                     cards it sat between are the invoice being built. "Add as
                     labour" still puts its line in the labour card. */}
                     labour" still puts its line in the labour card. */}
-                <JobClockSection
+                <JobClockSectionMemo
                   serviceRecordId={record.id}
                   serviceRecordId={record.id}
                   initial={props.jobClock}
                   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
                 <AppCard
@@ -537,7 +593,7 @@ export function ModernDetails(props: ModernDetailsProps) {
                         setStatus={formState.dirtySetStatus}
                         setStatus={formState.dirtySetStatus}
                         onDirty={formState.markDirty}
                         onDirty={formState.markDirty}
                         paymentStatus={formState.paymentStatus}
                         paymentStatus={formState.paymentStatus}
-                        onTogglePaid={actions.handleTogglePaid}
+                        onTogglePaid={onTogglePaid}
                         designOptions={props.designOptions}
                         designOptions={props.designOptions}
                         designId={record.designId ?? null}
                         designId={record.designId ?? null}
                         designFollowsName={props.designFollowsName}
                         designFollowsName={props.designFollowsName}
@@ -629,7 +685,7 @@ export function ModernDetails(props: ModernDetailsProps) {
                 )}
                 )}
 
 
                 <Lockable locked={locked}>
                 <Lockable locked={locked}>
-                  <CustomFieldsForm
+                  <CustomFieldsFormMemo
                     entityId={record.id}
                     entityId={record.id}
                     entityType="service_record"
                     entityType="service_record"
                     locked={locked}
                     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), [])
+}