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

Hide the support button on phones and tablets (#615)

* Hide the support button on phones and tablets

* Add a support entry to the phone menu and the sidebar account menu
Bernt Christian Egeland 1 день назад
Родитель
Сommit
f446f7de4f

+ 32 - 1
src/__tests__/components/mobile-bottom-nav.test.tsx

@@ -7,7 +7,7 @@
  */
 
 import { describe, it, expect, vi } from 'vitest'
-import { render, screen } from '@testing-library/react'
+import { act, render, screen } from '@testing-library/react'
 import { ServiceTypeProvider } from '@/components/service-type-context'
 
 vi.mock('next/navigation', () => ({
@@ -57,4 +57,35 @@ describe('MobileBottomNav', () => {
     expect(link.querySelector('.lucide-ship')).not.toBeNull()
     expect(screen.queryByRole('link', { name: 'Vehicles' })).toBeNull()
   })
+
+  // The floating support button is not drawn on a phone, and Settings >
+  // Support is closed to a role without settings access.
+  it('opens the support form from More when support is on', async () => {
+    const opened = vi.fn()
+    window.addEventListener('torqvoice:support:open', opened)
+    render(
+      <ServiceTypeProvider serviceType="automotive">
+        <MobileBottomNav supportEnabled />
+      </ServiceTypeProvider>
+    )
+
+    act(() => screen.getByRole('button', { name: 'More' }).click())
+    const contact = await screen.findByRole('button', { name: 'Contact support' })
+    await act(async () => {
+      contact.click()
+      await new Promise((resolve) => setTimeout(resolve, 300))
+    })
+
+    expect(opened).toHaveBeenCalled()
+    window.removeEventListener('torqvoice:support:open', opened)
+  })
+
+  it('has no support entry in More when support is off', async () => {
+    renderNav('automotive')
+
+    act(() => screen.getByRole('button', { name: 'More' }).click())
+    await screen.findByRole('link', { name: 'Settings' })
+
+    expect(screen.queryByRole('button', { name: 'Contact support' })).toBeNull()
+  })
 })

+ 163 - 0
src/__tests__/features/support/support-bubble-touch-screens.test.tsx

@@ -0,0 +1,163 @@
+import { act, render, screen } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { SupportBubble } from '@/features/support/Components/SupportBubble'
+import { SupportSettingsControls } from '@/features/support/Components/SupportSettingsControls'
+import {
+  SUPPORT_OPEN_EVENT,
+  openSupport,
+  setSupportBubbleHidden,
+} from '@/features/support/Lib/supportVisibility'
+
+// On a phone or tablet the floating support button sat on top of the buttons
+// being tapped. It is not drawn there, and neither is the edge tab a dismissed
+// button collapses to. Support stays reachable from Settings, which opens the
+// form through openSupport().
+
+function onDevice(kind: 'touch' | 'desktop') {
+  vi.stubGlobal(
+    'matchMedia',
+    vi.fn().mockImplementation((query: string) => ({
+      matches: kind === 'touch' && query.includes('pointer: coarse'),
+      // The sidebar's own phone check still uses the older listener pair.
+      addListener: vi.fn(),
+      removeListener: vi.fn(),
+      media: query,
+      addEventListener: vi.fn(),
+      removeEventListener: vi.fn(),
+    }))
+  )
+}
+
+async function contactSupportFromSettings() {
+  await act(async () => {
+    openSupport()
+    await new Promise((resolve) => requestAnimationFrame(resolve))
+  })
+}
+
+beforeEach(() => {
+  window.sessionStorage.clear()
+  window.localStorage.clear()
+})
+
+afterEach(() => {
+  vi.unstubAllGlobals()
+})
+
+describe('The support button on a phone or tablet', () => {
+  it('is not on screen', () => {
+    onDevice('touch')
+    render(<SupportBubble userId="anna" />)
+
+    expect(screen.queryByRole('button', { name: 'Contact support' })).not.toBeInTheDocument()
+  })
+
+  it('leaves no edge tab behind for someone who dismissed it on a computer', () => {
+    onDevice('touch')
+    setSupportBubbleHidden(true)
+    const { container } = render(<SupportBubble userId="anna" />)
+
+    expect(container).toBeEmptyDOMElement()
+  })
+
+  it('still opens the form when Settings asks for it, and is gone again once closed', async () => {
+    onDevice('touch')
+    render(<SupportBubble userId="anna" />)
+
+    await contactSupportFromSettings()
+    expect(screen.getByLabelText('Subject')).toBeInTheDocument()
+
+    act(() => screen.getByRole('button', { name: 'Close' }).click())
+    expect(screen.queryByLabelText('Subject')).not.toBeInTheDocument()
+    expect(screen.queryByRole('button', { name: 'Contact support' })).not.toBeInTheDocument()
+  })
+
+  it('is still there on a computer', () => {
+    onDevice('desktop')
+    render(<SupportBubble userId="anna" />)
+
+    expect(screen.getByRole('button', { name: 'Contact support' })).toBeInTheDocument()
+  })
+
+  it('opens the form for someone who dismissed the button on a computer', async () => {
+    onDevice('touch')
+    setSupportBubbleHidden(true)
+    render(<SupportBubble userId="anna" />)
+
+    await contactSupportFromSettings()
+
+    expect(screen.getByLabelText('Subject')).toBeInTheDocument()
+  })
+
+  it('opens the form from the backup page, which asks for it without a subject', async () => {
+    onDevice('touch')
+    render(<SupportBubble userId="anna" />)
+
+    await act(async () => {
+      window.dispatchEvent(new Event(SUPPORT_OPEN_EVENT))
+    })
+
+    expect(screen.getByLabelText('Subject')).toBeInTheDocument()
+  })
+
+  it('opens the form with the subject a page hands over', async () => {
+    onDevice('touch')
+    render(<SupportBubble userId="anna" />)
+
+    await act(async () => {
+      openSupport({ subject: 'Fault code P0420' })
+      await new Promise((resolve) => requestAnimationFrame(resolve))
+    })
+
+    expect(screen.getByLabelText('Subject')).toHaveValue('Fault code P0420')
+  })
+
+  it('does not offer to hide a button that is not there', async () => {
+    onDevice('touch')
+    render(<SupportBubble userId="anna" />)
+
+    await contactSupportFromSettings()
+
+    expect(
+      screen.queryByRole('button', { name: 'Hide the support button' })
+    ).not.toBeInTheDocument()
+    expect(screen.getByRole('button', { name: 'Send request' })).toBeInTheDocument()
+  })
+
+  it('still offers to hide the button on a computer', async () => {
+    onDevice('desktop')
+    render(<SupportBubble userId="anna" />)
+
+    act(() => screen.getByRole('button', { name: 'Contact support' }).click())
+
+    expect(screen.getByRole('button', { name: 'Hide the support button' })).toBeInTheDocument()
+  })
+})
+
+describe('Settings > Support on a phone or tablet', () => {
+  it('has no switch for the button, and Open form opens the form', async () => {
+    onDevice('touch')
+    render(
+      <>
+        <SupportSettingsControls />
+        <SupportBubble userId="anna" />
+      </>
+    )
+
+    expect(screen.queryByRole('switch')).not.toBeInTheDocument()
+    expect(screen.queryByText('Show the support button')).not.toBeInTheDocument()
+
+    await act(async () => {
+      screen.getByRole('button', { name: 'Open form' }).click()
+      await new Promise((resolve) => requestAnimationFrame(resolve))
+    })
+    expect(screen.getByLabelText('Subject')).toBeInTheDocument()
+  })
+
+  it('keeps the switch on a computer', () => {
+    onDevice('desktop')
+    render(<SupportSettingsControls />)
+
+    expect(screen.getByRole('switch', { name: 'Show the support button' })).toBeInTheDocument()
+  })
+})

+ 2 - 0
src/app/(authenticated)/layout.tsx

@@ -448,6 +448,7 @@ export default async function DashboardLayout({ children }: { children: React.Re
                                     isAdminOrOwner={isOwnerOrAdmin}
                                     counts={sidebarCounts}
                                     isTechnician={technicianIds.length > 0}
+                                    supportEnabled={supportEnabled}
                                   />
                                   <SidebarInset
                                     id="main-content"
@@ -495,6 +496,7 @@ export default async function DashboardLayout({ children }: { children: React.Re
                   <MobileBottomNav
                     isSuperAdmin={data.isSuperAdmin}
                     tireHotelEnabled={tireHotelEnabled}
+                    supportEnabled={supportEnabled}
                   />
                   {supportEnabled && <SupportBubble userId={data.userId} />}
                 </ShortcutsProvider>

+ 23 - 0
src/components/app-sidebar.tsx

@@ -65,6 +65,7 @@ import {
   LogOut,
   Monitor,
   Package,
+  Headset,
   Keyboard,
   Palette,
   Plus,
@@ -97,6 +98,8 @@ import { FullscreenLauncher, FullscreenMenuItem } from '@/components/fullscreen-
 import { FeatureHint } from '@/components/feature-hint'
 import { ANNOUNCEMENTS } from '@/features/settings/Lib/featureHints'
 import { cn } from '@/lib/utils'
+import { openSupport } from '@/features/support/Lib/supportVisibility'
+import { useTouchScreen } from '@/features/support/Lib/useTouchScreen'
 import { handleGated } from '@/components/upgrade-gate'
 
 type OrgInfo = { id: string; name: string; role: string }
@@ -156,6 +159,7 @@ export function AppSidebar({
   announcement = null,
   counts,
   isTechnician = false,
+  supportEnabled = false,
   ...props
 }: React.ComponentProps<typeof Sidebar> & {
   companyLogo?: string
@@ -175,6 +179,7 @@ export function AppSidebar({
   counts?: SidebarCounts
   /** Linked to a technician row: the dashboard is their job list even without the figures. */
   isTechnician?: boolean
+  supportEnabled?: boolean
 }) {
   const pathname = usePathname()
   const { openHelp: openShortcutsHelp } = useShortcuts()
@@ -187,6 +192,8 @@ export function AppSidebar({
   const t = useTranslations('navigation')
   const tHint = useTranslations('featureHints')
   const tSettings = useTranslations('settings')
+  const tSupport = useTranslations('support')
+  const touchScreen = useTouchScreen()
   const [showCreateOrg, setShowCreateOrg] = React.useState(false)
   const [newOrgName, setNewOrgName] = React.useState('')
   const [creatingOrg, setCreatingOrg] = React.useState(false)
@@ -700,6 +707,22 @@ export function AppSidebar({
                     </Link>
                   </DropdownMenuItem>
                 )}
+                {/* A phone or tablet has no floating support button, and the
+                    settings page that opens the form turns away a role
+                    without settings access. */}
+                {supportEnabled && touchScreen && (
+                  <DropdownMenuItem
+                    onSelect={() => {
+                      // On a phone the sidebar is a sheet over the page; the
+                      // form would open underneath it.
+                      if (isMobile) setOpenMobile(false)
+                      openSupport()
+                    }}
+                  >
+                    <Headset className="mr-2 size-4" />
+                    {tSupport('open')}
+                  </DropdownMenuItem>
+                )}
                 <DropdownMenuItem onSelect={openShortcutsHelp}>
                   <Keyboard className="mr-2 size-4" />
                   {t('sidebar.keyboardShortcuts')}

+ 23 - 0
src/components/mobile-bottom-nav.tsx

@@ -15,6 +15,7 @@ import {
   Columns3,
   Disc3,
   FileText,
+  Headset,
   History,
   Layers,
   Loader2,
@@ -47,6 +48,7 @@ import {
   getInventoryPart,
 } from '@/features/inventory/Actions/inventoryActions'
 import { Separator } from '@/components/ui/separator'
+import { openSupport } from '@/features/support/Lib/supportVisibility'
 import { cn } from '@/lib/utils'
 import { toast } from 'sonner'
 
@@ -90,9 +92,11 @@ const allDrawerItems = [
 export function MobileBottomNav({
   isSuperAdmin,
   tireHotelEnabled,
+  supportEnabled,
 }: {
   isSuperAdmin?: boolean
   tireHotelEnabled?: boolean
+  supportEnabled?: boolean
 }) {
   const pathname = usePathname()
   const isMarine = useServiceType() === 'marine'
@@ -103,6 +107,7 @@ export function MobileBottomNav({
   const router = useRouter()
   const t = useTranslations('navigation.sidebar')
   const tScan = useTranslations('inventory.barcodeScan')
+  const tSupport = useTranslations('support')
   const ta = useTranslations('common.a11y')
   const [drawerOpen, setDrawerOpen] = useState(false)
   const [scannerOpen, setScannerOpen] = useState(false)
@@ -273,6 +278,24 @@ export function MobileBottomNav({
                 <Settings className="h-5 w-5" />
                 <span>{t('settings')}</span>
               </Link>
+              {/* A phone has no floating support button, and the settings
+                  page that opens the form turns away a role without settings
+                  access. This is the way in for everyone. */}
+              {supportEnabled && (
+                <button
+                  type="button"
+                  onClick={() => {
+                    setDrawerOpen(false)
+                    // After the drawer has let go of the page, or it takes
+                    // the focus back from the form.
+                    setTimeout(() => openSupport(), 200)
+                  }}
+                  className="flex flex-col items-center gap-1.5 rounded-lg py-3 text-center text-xs text-muted-foreground transition-colors hover:bg-accent"
+                >
+                  <Headset className="h-5 w-5" />
+                  <span>{tSupport('open')}</span>
+                </button>
+              )}
               {isSuperAdmin && (
                 <Link
                   href="/admin"

+ 53 - 22
src/features/support/Components/SupportBubble.tsx

@@ -37,6 +37,7 @@ import {
   setSupportBubbleHidden,
 } from '@/features/support/Lib/supportVisibility'
 import { useDraggablePosition } from '@/features/support/Lib/useDraggablePosition'
+import { useTouchScreen } from '@/features/support/Lib/useTouchScreen'
 
 type Status = 'idle' | 'sending' | 'sent'
 
@@ -94,6 +95,13 @@ export function SupportBubble({ userId }: { userId: string }) {
     }
   }, [])
 
+  // On a phone or tablet the floating button sits on top of what is being
+  // tapped, so neither it nor its edge tab is drawn there. Support is still a
+  // tap away in Settings, and the form opens as usual when a page asks for it.
+  // Unknown for the first render: nothing is drawn until it is known, so the
+  // button never shows for a frame on a phone.
+  const touchScreen = useTouchScreen()
+
   /**
    * The panel follows the button. It is right-aligned to the button and opens
    * upward when the button sits low, which is where it usually will after being
@@ -268,12 +276,16 @@ export function SupportBubble({ userId }: { userId: string }) {
   )
 
   // position is null until localStorage and the viewport have been read.
-  if (!position) return null
+  if (!position || touchScreen === null) return null
+
+  // Only the form, and only while it is open. The dismissal below is about
+  // the button, so it has no say here.
+  if (touchScreen && !isOpen) return null
 
   // Dismissed collapses to a tab tucked against the right edge rather than
   // disappearing. Removing the button outright leaves no way back except the
   // settings page, which is not somewhere you look when you want support.
-  if (hidden) {
+  if (hidden && !touchScreen) {
     return (
       <button
         type="button"
@@ -319,25 +331,41 @@ export function SupportBubble({ userId }: { userId: string }) {
 
       {isOpen && (
         <div
-          style={panelStyle}
-          className="fixed z-50 overflow-hidden rounded-xl border bg-popover shadow-2xl ring-1 ring-black/5 dark:ring-white/10"
+          // With no button to follow, the form sits at the top of the screen:
+          // clear of the bottom navigation, and of the on-screen keyboard that
+          // covers the lower half as soon as a field is tapped. Below a
+          // laptop's width it hangs from the left edge: a page that is a few
+          // pixels too wide pushes the right edge, and the close button with
+          // it, off a phone or small tablet.
+          style={touchScreen ? undefined : panelStyle}
+          className={`fixed z-50 overflow-hidden rounded-xl border bg-popover shadow-2xl ring-1 ring-black/5 dark:ring-white/10 ${
+            touchScreen
+              ? 'top-[calc(0.75rem+env(safe-area-inset-top))] left-3 w-[min(380px,calc(100vw-1.5rem))] lg:right-3 lg:left-auto'
+              : ''
+          }`}
         >
-          <div className="flex items-center gap-1 border-b bg-muted/40 py-2 pl-1 pr-2">
+          <div
+            className={`flex items-center gap-1 border-b bg-muted/40 py-2 pr-2 ${
+              touchScreen ? 'pl-3' : 'pl-1'
+            }`}
+          >
             {/* Hidden from assistive tech rather than announced as a button.
                 Dragging is pointer-only, so exposing it as a control would
                 advertise something a keyboard user cannot operate. Nothing is
                 lost: every control in the panel is reachable regardless of
                 where it sits, and the position is only a convenience. */}
-            <span
-              {...dragHandlers}
-              aria-hidden="true"
-              title={t('move')}
-              className={`flex h-7 w-6 shrink-0 touch-none items-center justify-center text-muted-foreground/60 hover:text-muted-foreground ${
-                dragging ? 'cursor-grabbing' : 'cursor-grab'
-              }`}
-            >
-              <GripVertical className="h-4 w-4" />
-            </span>
+            {!touchScreen && (
+              <span
+                {...dragHandlers}
+                aria-hidden="true"
+                title={t('move')}
+                className={`flex h-7 w-6 shrink-0 touch-none items-center justify-center text-muted-foreground/60 hover:text-muted-foreground ${
+                  dragging ? 'cursor-grabbing' : 'cursor-grab'
+                }`}
+              >
+                <GripVertical className="h-4 w-4" />
+              </span>
+            )}
             <Headset className="h-4 w-4 shrink-0 text-primary" strokeWidth={1.75} />
             <span className="flex-1 truncate text-sm font-medium">{t('title')}</span>
             <button
@@ -477,13 +505,16 @@ export function SupportBubble({ userId }: { userId: string }) {
                   {status === 'sending' ? t('sending') : t('send')}
                 </Button>
 
-                <button
-                  type="button"
-                  onClick={handleDismiss}
-                  className="w-full text-center text-xs text-muted-foreground transition-colors hover:text-foreground hover:underline"
-                >
-                  {t('hideButton')}
-                </button>
+                {/* There is no button to hide on a phone or tablet. */}
+                {!touchScreen && (
+                  <button
+                    type="button"
+                    onClick={handleDismiss}
+                    className="w-full text-center text-xs text-muted-foreground transition-colors hover:text-foreground hover:underline"
+                  >
+                    {t('hideButton')}
+                  </button>
+                )}
               </form>
             )}
           </div>

+ 24 - 16
src/features/support/Components/SupportSettingsControls.tsx

@@ -12,6 +12,7 @@ import {
   openSupport,
   setSupportBubbleHidden,
 } from '@/features/support/Lib/supportVisibility'
+import { useTouchScreen } from '@/features/support/Lib/useTouchScreen'
 
 /**
  * The way back for someone who dismissed the button. Reads and writes the same
@@ -24,6 +25,9 @@ export function SupportSettingsControls() {
   // Rendered on the server first, so the stored preference is unknown until
   // mount. Without this the switch flips visibly on load.
   const [ready, setReady] = useState(false)
+  // A phone or tablet has no floating button, so there is nothing to switch
+  // on or off there. The classes on the row hide it before this is known.
+  const touchScreen = useTouchScreen()
 
   useEffect(() => {
     const sync = () => setVisible(!isSupportBubbleHidden())
@@ -39,23 +43,27 @@ export function SupportSettingsControls() {
 
   return (
     <div className="space-y-4">
-      <div className="flex items-center justify-between gap-4">
-        <div className="space-y-0.5">
-          <Label htmlFor="support-visible">{t('support.showButton')}</Label>
-          <p className="text-xs text-muted-foreground">{t('support.showButtonHint')}</p>
-        </div>
-        <Switch
-          id="support-visible"
-          checked={visible}
-          disabled={!ready}
-          onCheckedChange={(checked) => {
-            setVisible(checked)
-            setSupportBubbleHidden(!checked)
-          }}
-        />
-      </div>
+      {!touchScreen && (
+        <div className="space-y-4 max-lg:hidden pointer-coarse:hidden">
+          <div className="flex items-center justify-between gap-4">
+            <div className="space-y-0.5">
+              <Label htmlFor="support-visible">{t('support.showButton')}</Label>
+              <p className="text-xs text-muted-foreground">{t('support.showButtonHint')}</p>
+            </div>
+            <Switch
+              id="support-visible"
+              checked={visible}
+              disabled={!ready}
+              onCheckedChange={(checked) => {
+                setVisible(checked)
+                setSupportBubbleHidden(!checked)
+              }}
+            />
+          </div>
 
-      <Separator />
+          <Separator />
+        </div>
+      )}
 
       <div id="support-contact" className="flex items-center justify-between gap-4">
         <div className="space-y-0.5">

+ 33 - 0
src/features/support/Lib/useTouchScreen.ts

@@ -0,0 +1,33 @@
+'use client'
+
+import { useEffect, useState } from 'react'
+
+/**
+ * Phones and tablets: a finger as the main pointer, or a screen narrower than
+ * a laptop's. A touchscreen laptop keeps the button, its main pointer is a mouse.
+ */
+export const TOUCH_SCREEN_QUERY = '(pointer: coarse), (max-width: 1023px)'
+
+/**
+ * Whether this is a phone or tablet, where the floating support button is not
+ * drawn. `null` until the browser has been asked, so a caller can hold back
+ * what it would otherwise have to pull away a frame later.
+ */
+export function useTouchScreen(): boolean | null {
+  const [touchScreen, setTouchScreen] = useState<boolean | null>(null)
+
+  useEffect(() => {
+    const query = window.matchMedia?.(TOUCH_SCREEN_QUERY)
+    if (!query) {
+      setTouchScreen(false)
+      return
+    }
+    const sync = () => setTouchScreen(query.matches)
+    sync()
+    // Rotating a small tablet or resizing a window moves it across the line.
+    query.addEventListener('change', sync)
+    return () => query.removeEventListener('change', sync)
+  }, [])
+
+  return touchScreen
+}