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

Keep the support button in its corner when the window is resized (#654)

* Keep the support button in its corner when the window is resized

* Test the resize with the button hidden below laptop width, as in the app

* Keep a place saved by an earlier build until a window fits it, then save it by its corner
Bernt Christian Egeland 6 дней назад
Родитель
Сommit
a071f61b30

+ 268 - 0
src/__tests__/features/support/support-bubble-window-resize.test.tsx

@@ -0,0 +1,268 @@
+import { act, fireEvent, render, screen } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { SupportBubble } from '@/features/support/Components/SupportBubble'
+
+// The support button belongs to a corner of the window. A tab that had been in
+// a small window kept the place the small window forced on it, so making the
+// window large again left the button in the middle of the screen. Below a
+// laptop's width the button is not drawn at all, which is why nobody saw it
+// move until the window was large again.
+
+const LARGE = { width: 1440, height: 900 }
+const SMALL = { width: 390, height: 600 }
+/** Wide enough to keep the button, too short for where it was. */
+const SHORT = { width: 1100, height: 420 }
+const BUTTON = 48
+
+function windowIs(size: { width: number; height: number }) {
+  Object.defineProperty(window, 'innerWidth', { configurable: true, value: size.width })
+  Object.defineProperty(window, 'innerHeight', { configurable: true, value: size.height })
+}
+
+/** Listeners the page has on its media queries, told when the window changes. */
+const mediaListeners = new Set<() => void>()
+
+function resizeWindowTo(size: { width: number; height: number }) {
+  act(() => {
+    windowIs(size)
+    window.dispatchEvent(new Event('resize'))
+    for (const listener of mediaListeners) listener()
+  })
+}
+
+function button() {
+  return screen.getByRole('button', { name: 'Contact support' })
+}
+
+function expectNoButton() {
+  expect(screen.queryByRole('button', { name: 'Contact support' })).not.toBeInTheDocument()
+}
+
+/** Where the button is, as its distance to each edge of the window. */
+function place() {
+  const left = Number.parseFloat(button().style.left)
+  const top = Number.parseFloat(button().style.top)
+  return {
+    left,
+    top,
+    right: window.innerWidth - left - BUTTON,
+    bottom: window.innerHeight - top - BUTTON,
+  }
+}
+
+function expectFullyOnScreen() {
+  const { left, top, right, bottom } = place()
+  expect(left).toBeGreaterThanOrEqual(0)
+  expect(top).toBeGreaterThanOrEqual(0)
+  expect(right).toBeGreaterThanOrEqual(0)
+  expect(bottom).toBeGreaterThanOrEqual(0)
+}
+
+function pointer(type: string, x: number, y: number) {
+  const event = new MouseEvent(type, {
+    bubbles: true,
+    cancelable: true,
+    button: 0,
+    clientX: x,
+    clientY: y,
+  })
+  Object.defineProperty(event, 'pointerId', { value: 1 })
+  return event
+}
+
+/** Drags the button so that its top-left corner ends at the given point. */
+function dragButtonTo(x: number, y: number) {
+  const from = place()
+  const target = button()
+  act(() => {
+    fireEvent(target, pointer('pointerdown', from.left + 10, from.top + 10))
+  })
+  act(() => {
+    fireEvent(target, pointer('pointermove', x + 10, y + 10))
+  })
+  act(() => {
+    fireEvent(target, pointer('pointerup', x + 10, y + 10))
+  })
+}
+
+beforeEach(() => {
+  window.sessionStorage.clear()
+  window.localStorage.clear()
+  vi.stubGlobal(
+    'matchMedia',
+    // A computer with a mouse: the only thing that hides the button is a
+    // window narrower than a laptop's.
+    vi.fn().mockImplementation((query: string) => ({
+      get matches() {
+        return query.includes('max-width: 1023px') && window.innerWidth < 1024
+      },
+      media: query,
+      addListener: vi.fn(),
+      removeListener: vi.fn(),
+      addEventListener: (_: string, listener: () => void) => mediaListeners.add(listener),
+      removeEventListener: (_: string, listener: () => void) => mediaListeners.delete(listener),
+    }))
+  )
+  windowIs(LARGE)
+})
+
+afterEach(() => {
+  mediaListeners.clear()
+  vi.unstubAllGlobals()
+  windowIs({ width: 1024, height: 768 })
+})
+
+describe('The support button when the window changes size', () => {
+  it('is back in its corner when a window that was made small is large again', () => {
+    render(<SupportBubble userId="anna" />)
+    expect(place()).toMatchObject({ right: 24, bottom: 24 })
+
+    resizeWindowTo(SMALL)
+    expectNoButton()
+
+    resizeWindowTo(LARGE)
+    expect(place()).toMatchObject({ right: 24, bottom: 24 })
+  })
+
+  it('goes to the corner of the large window when the tab was opened in a small one', () => {
+    windowIs(SMALL)
+    render(<SupportBubble userId="anna" />)
+    expectNoButton()
+
+    resizeWindowTo(LARGE)
+    expect(place()).toMatchObject({ right: 24, bottom: 24 })
+  })
+
+  it('stays in its corner, fully on screen, in a window that is only made shorter', () => {
+    render(<SupportBubble userId="anna" />)
+
+    resizeWindowTo(SHORT)
+    expect(place()).toMatchObject({ right: 24, bottom: 24 })
+
+    resizeWindowTo(LARGE)
+    expect(place()).toMatchObject({ right: 24, bottom: 24 })
+  })
+
+  it('keeps a dragged button the same distance from the corner it was left near', () => {
+    render(<SupportBubble userId="anna" />)
+    dragButtonTo(1200, 200)
+    expect(place()).toMatchObject({ left: 1200, top: 200 })
+    const chosen = place()
+
+    // Too short and too narrow for where it was: pushed inward, not lost.
+    resizeWindowTo(SHORT)
+    expectFullyOnScreen()
+    resizeWindowTo(SMALL)
+    expectNoButton()
+
+    resizeWindowTo(LARGE)
+    expect(place()).toEqual(chosen)
+
+    resizeWindowTo({ width: 1920, height: 1080 })
+    expect(place()).toMatchObject({ right: chosen.right, top: 200 })
+  })
+
+  it('keeps a button dragged to the left side on the left', () => {
+    render(<SupportBubble userId="anna" />)
+    dragButtonTo(40, 700)
+
+    resizeWindowTo(SMALL)
+    resizeWindowTo({ width: 1920, height: 1080 })
+
+    expect(place()).toMatchObject({ left: 40, bottom: 900 - 700 - BUTTON })
+  })
+
+  it('remembers where it was dragged after a reload, also one made in a smaller window', () => {
+    const first = render(<SupportBubble userId="anna" />)
+    dragButtonTo(1200, 200)
+    const chosen = place()
+    first.unmount()
+
+    windowIs(SHORT)
+    render(<SupportBubble userId="anna" />)
+    expectFullyOnScreen()
+
+    resizeWindowTo(LARGE)
+    expect(place()).toEqual(chosen)
+  })
+
+  describe('with a place saved before this change, as pixels from the top-left', () => {
+    function savedByAnEarlierBuild(x: number, y: number) {
+      window.localStorage.setItem('torqvoice.support.position', JSON.stringify({ x, y }))
+    }
+
+    it('is still where it was, and comes back there after a small window', () => {
+      savedByAnEarlierBuild(1200, 200)
+      render(<SupportBubble userId="anna" />)
+      expect(place()).toMatchObject({ left: 1200, top: 200 })
+
+      resizeWindowTo(SMALL)
+      resizeWindowTo(LARGE)
+
+      expect(place()).toMatchObject({ left: 1200, top: 200 })
+    })
+
+    it('goes back to it when the tab was first opened in a window too small for it', () => {
+      savedByAnEarlierBuild(1200, 700)
+      windowIs(SHORT)
+      render(<SupportBubble userId="anna" />)
+      expectFullyOnScreen()
+
+      resizeWindowTo(LARGE)
+
+      expect(place()).toMatchObject({ left: 1200, top: 700 })
+    })
+
+    it('is not lost by a reload in a window too small for it', () => {
+      savedByAnEarlierBuild(1200, 700)
+      windowIs(SHORT)
+      const first = render(<SupportBubble userId="anna" />)
+      first.unmount()
+      windowIs(SMALL)
+      const second = render(<SupportBubble userId="anna" />)
+      second.unmount()
+
+      windowIs(LARGE)
+      render(<SupportBubble userId="anna" />)
+
+      expect(place()).toMatchObject({ left: 1200, top: 700 })
+    })
+
+    it('keeps its distance to the corner after a resize followed by a reload', () => {
+      savedByAnEarlierBuild(1200, 700)
+      const first = render(<SupportBubble userId="anna" />)
+      const chosen = place()
+      resizeWindowTo(SHORT)
+      first.unmount()
+
+      render(<SupportBubble userId="anna" />)
+      expectFullyOnScreen()
+      resizeWindowTo(LARGE)
+      expect(place()).toEqual(chosen)
+
+      resizeWindowTo({ width: 1920, height: 1080 })
+      expect(place()).toMatchObject({ right: chosen.right, bottom: chosen.bottom })
+    })
+
+    it('gives way to a new place the moment the button is dragged', () => {
+      savedByAnEarlierBuild(1200, 700)
+      windowIs(SHORT)
+      render(<SupportBubble userId="anna" />)
+      dragButtonTo(40, 100)
+
+      resizeWindowTo(LARGE)
+
+      expect(place()).toMatchObject({ left: 40, top: 100 })
+    })
+  })
+
+  it('opens the form on the click after a resize, not a drag', () => {
+    render(<SupportBubble userId="anna" />)
+    resizeWindowTo(SMALL)
+    resizeWindowTo(LARGE)
+
+    act(() => button().click())
+
+    expect(screen.getByLabelText('Subject')).toBeInTheDocument()
+  })
+})

+ 53 - 14
src/features/support/Lib/supportVisibility.ts

@@ -53,23 +53,43 @@ export function isSupportBubbleHidden(): boolean {
   }
 }
 
-/** Where this person dragged the button to, as the trigger's top-left corner. */
+/**
+ * Where the button sat before its place was kept relative to a corner: the
+ * trigger's top-left corner in pixels. Still read, so a place chosen before
+ * that change is not lost, and never written.
+ */
 export const SUPPORT_POSITION_STORAGE_KEY = 'torqvoice.support.position'
 
+/** The trigger's top-left corner, in pixels from the top-left of the window. */
 export interface SupportPosition {
   x: number
   y: number
 }
 
-export function readSupportPosition(): SupportPosition | null {
+/** Where this person dragged the button to. */
+export const SUPPORT_ANCHOR_STORAGE_KEY = 'torqvoice.support.anchor'
+
+/**
+ * The button's place as a distance to the two window edges it was left
+ * nearest to. Pixels from the top-left only mean something in the window they
+ * were measured in: a place near the bottom right of a large window is off
+ * screen in a small one, and what a small window allows is the middle of a
+ * large one.
+ */
+export interface SupportAnchor {
+  horizontal: 'left' | 'right'
+  /** Distance from that side of the window to the same side of the button. */
+  x: number
+  vertical: 'top' | 'bottom'
+  /** Distance from that edge of the window to the same edge of the button. */
+  y: number
+}
+
+function readStored(key: string): unknown {
   if (typeof window === 'undefined') return null
   try {
-    const raw = window.localStorage.getItem(SUPPORT_POSITION_STORAGE_KEY)
-    if (!raw) return null
-    const parsed = JSON.parse(raw)
-    if (typeof parsed?.x !== 'number' || typeof parsed?.y !== 'number') return null
-    if (!Number.isFinite(parsed.x) || !Number.isFinite(parsed.y)) return null
-    return { x: parsed.x, y: parsed.y }
+    const raw = window.localStorage.getItem(key)
+    return raw ? JSON.parse(raw) : null
   } catch {
     // Corrupt or unreadable storage falls back to the default corner rather
     // than leaving the button unrenderable.
@@ -77,14 +97,33 @@ export function readSupportPosition(): SupportPosition | null {
   }
 }
 
-export function writeSupportPosition(position: SupportPosition | null): void {
+function isDistance(value: unknown): value is number {
+  return typeof value === 'number' && Number.isFinite(value)
+}
+
+export function readSupportAnchor(): SupportAnchor | null {
+  const parsed = readStored(SUPPORT_ANCHOR_STORAGE_KEY) as Partial<SupportAnchor> | null
+  if (!parsed || typeof parsed !== 'object') return null
+  if (parsed.horizontal !== 'left' && parsed.horizontal !== 'right') return null
+  if (parsed.vertical !== 'top' && parsed.vertical !== 'bottom') return null
+  if (!isDistance(parsed.x) || !isDistance(parsed.y)) return null
+  return { horizontal: parsed.horizontal, x: parsed.x, vertical: parsed.vertical, y: parsed.y }
+}
+
+/** A place saved by a build that kept pixels from the top-left. */
+export function readLegacySupportPosition(): SupportPosition | null {
+  const parsed = readStored(SUPPORT_POSITION_STORAGE_KEY) as Partial<SupportPosition> | null
+  if (!parsed || typeof parsed !== 'object') return null
+  if (!isDistance(parsed.x) || !isDistance(parsed.y)) return null
+  return { x: parsed.x, y: parsed.y }
+}
+
+export function writeSupportAnchor(anchor: SupportAnchor): void {
   if (typeof window === 'undefined') return
   try {
-    if (position) {
-      window.localStorage.setItem(SUPPORT_POSITION_STORAGE_KEY, JSON.stringify(position))
-    } else {
-      window.localStorage.removeItem(SUPPORT_POSITION_STORAGE_KEY)
-    }
+    window.localStorage.setItem(SUPPORT_ANCHOR_STORAGE_KEY, JSON.stringify(anchor))
+    // Superseded, and would otherwise come back if the new key were cleared.
+    window.localStorage.removeItem(SUPPORT_POSITION_STORAGE_KEY)
     window.dispatchEvent(new Event(SUPPORT_VISIBILITY_EVENT))
   } catch {
     // The position simply will not persist.

+ 108 - 25
src/features/support/Lib/useDraggablePosition.ts

@@ -1,10 +1,12 @@
 'use client'
 
-import { useCallback, useEffect, useRef, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
 import {
-  readSupportPosition,
-  writeSupportPosition,
+  readLegacySupportPosition,
+  readSupportAnchor,
+  type SupportAnchor,
   type SupportPosition,
+  writeSupportAnchor,
 } from './supportVisibility'
 
 /** Distance to the viewport edges the button is never allowed to cross. */
@@ -16,24 +18,64 @@ const EDGE_MARGIN = 8
  */
 const MOBILE_NAV_HEIGHT = 56
 
+interface Viewport {
+  width: number
+  height: number
+}
+
+function readViewport(): Viewport {
+  return { width: window.innerWidth, height: window.innerHeight }
+}
+
 function clamp(value: number, min: number, max: number): number {
   // max can fall below min on a very small viewport; min wins so the button
   // stays reachable rather than being pushed off the top.
   return Math.max(min, Math.min(value, max))
 }
 
-function defaultPosition(size: number): SupportPosition {
-  const isMobile = window.innerWidth < 768
+/** The bottom right corner, clear of the bottom navigation in a narrow window. */
+function defaultAnchor(viewport: Viewport): SupportAnchor {
+  const isMobile = viewport.width < 768
   return {
-    x: window.innerWidth - size - (isMobile ? 16 : 24),
-    y: window.innerHeight - size - (isMobile ? MOBILE_NAV_HEIGHT + 16 : 24),
+    horizontal: 'right',
+    x: isMobile ? 16 : 24,
+    vertical: 'bottom',
+    y: isMobile ? MOBILE_NAV_HEIGHT + 16 : 24,
   }
 }
 
-function clampToViewport(position: SupportPosition, size: number): SupportPosition {
+function clampToViewport(
+  position: SupportPosition,
+  size: number,
+  viewport: Viewport
+): SupportPosition {
   return {
-    x: clamp(position.x, EDGE_MARGIN, window.innerWidth - size - EDGE_MARGIN),
-    y: clamp(position.y, EDGE_MARGIN, window.innerHeight - size - EDGE_MARGIN),
+    x: clamp(position.x, EDGE_MARGIN, viewport.width - size - EDGE_MARGIN),
+    y: clamp(position.y, EDGE_MARGIN, viewport.height - size - EDGE_MARGIN),
+  }
+}
+
+/** Where an anchored button is drawn in a window of this size, kept on screen. */
+function resolveAnchor(anchor: SupportAnchor, size: number, viewport: Viewport): SupportPosition {
+  return clampToViewport(
+    {
+      x: anchor.horizontal === 'left' ? anchor.x : viewport.width - size - anchor.x,
+      y: anchor.vertical === 'top' ? anchor.y : viewport.height - size - anchor.y,
+    },
+    size,
+    viewport
+  )
+}
+
+/** Ties a place on screen to the two window edges it is nearest to. */
+function anchorFor(position: SupportPosition, size: number, viewport: Viewport): SupportAnchor {
+  const left = position.x + size / 2 < viewport.width / 2
+  const top = position.y + size / 2 < viewport.height / 2
+  return {
+    horizontal: left ? 'left' : 'right',
+    x: left ? position.x : viewport.width - size - position.x,
+    vertical: top ? 'top' : 'bottom',
+    y: top ? position.y : viewport.height - size - position.y,
   }
 }
 
@@ -45,11 +87,24 @@ function clampToViewport(position: SupportPosition, size: number): SupportPositi
  * every page, this lets the user move it and keeps that choice per device,
  * alongside the dismissal preference.
  *
+ * The place is kept as a distance to the nearest window edges and only turned
+ * into pixels for the window as it is now. A small window can push the button
+ * inward to keep it on screen, but that never replaces the place it belongs:
+ * making the window large again puts it back.
+ *
  * Pointer events rather than mouse events, so a touch drag works without a
  * second code path.
  */
 export function useDraggablePosition(size: number) {
-  const [position, setPosition] = useState<SupportPosition | null>(null)
+  // Null until dragged: the default corner, which depends on the window width.
+  const [anchor, setAnchor] = useState<SupportAnchor | null>(null)
+  // A place saved as pixels from the top-left by an earlier build, kept as it
+  // is until a window comes along that it fits in. The window it was measured
+  // in is not known, only that it was at least that large, so anchoring it to
+  // a smaller one would tie it to the wrong distance from the edges.
+  const [legacy, setLegacy] = useState<SupportPosition | null>(null)
+  // Null until the window has been measured, which only the browser can do.
+  const [viewport, setViewport] = useState<Viewport | null>(null)
   const [dragging, setDragging] = useState(false)
   // Set while a drag is in progress and cleared on the next click, so releasing
   // after a drag does not also open the panel.
@@ -57,25 +112,46 @@ export function useDraggablePosition(size: number) {
   const originRef = useRef<{ pointerX: number; pointerY: number; x: number; y: number } | null>(
     null
   )
+  // What the drag in progress will save when the pointer is released.
+  const draggedAnchorRef = useRef<SupportAnchor | null>(null)
 
   useEffect(() => {
-    const stored = readSupportPosition()
-    setPosition(clampToViewport(stored ?? defaultPosition(size), size))
-  }, [size])
+    const stored = readSupportAnchor()
+    setAnchor(stored)
+    setLegacy(stored ? null : readLegacySupportPosition())
+    setViewport(readViewport())
+  }, [])
 
-  // A window that shrinks, or a phone that rotates, can leave a stored position
-  // outside the viewport with no way to reach the button.
+  // The first window the old place fits in stands in for the one it was
+  // measured in: the button is drawn exactly where the earlier build drew it,
+  // and from then on it is saved relative to that window's edges, so a reload
+  // at another size no longer reads the old pixels again.
   useEffect(() => {
-    const onResize = () => {
-      setPosition((current) => (current ? clampToViewport(current, size) : current))
-    }
+    if (!legacy || !viewport) return
+    const shown = clampToViewport(legacy, size, viewport)
+    if (shown.x !== legacy.x || shown.y !== legacy.y) return
+    const converted = anchorFor(legacy, size, viewport)
+    writeSupportAnchor(converted)
+    setAnchor(converted)
+    setLegacy(null)
+  }, [legacy, viewport, size])
+
+  useEffect(() => {
+    const onResize = () => setViewport(readViewport())
     window.addEventListener('resize', onResize)
     window.addEventListener('orientationchange', onResize)
     return () => {
       window.removeEventListener('resize', onResize)
       window.removeEventListener('orientationchange', onResize)
     }
-  }, [size])
+  }, [])
+
+  const position = useMemo(() => {
+    if (!viewport) return null
+    if (anchor) return resolveAnchor(anchor, size, viewport)
+    if (legacy) return clampToViewport(legacy, size, viewport)
+    return resolveAnchor(defaultAnchor(viewport), size, viewport)
+  }, [anchor, legacy, viewport, size])
 
   const onPointerDown = useCallback(
     (event: React.PointerEvent) => {
@@ -112,7 +188,16 @@ export function useDraggablePosition(size: number) {
         movedRef.current = true
         setDragging(true)
       }
-      setPosition(clampToViewport({ x: origin.x + dx, y: origin.y + dy }, size))
+      const current = readViewport()
+      const next = anchorFor(
+        clampToViewport({ x: origin.x + dx, y: origin.y + dy }, size, current),
+        size,
+        current
+      )
+      draggedAnchorRef.current = next
+      setAnchor(next)
+      // Moved by hand: wherever an earlier build had it no longer matters.
+      setLegacy(null)
     },
     [size]
   )
@@ -122,10 +207,8 @@ export function useDraggablePosition(size: number) {
     originRef.current = null
     if (movedRef.current) {
       setDragging(false)
-      setPosition((current) => {
-        if (current) writeSupportPosition(current)
-        return current
-      })
+      if (draggedAnchorRef.current) writeSupportAnchor(draggedAnchorRef.current)
+      draggedAnchorRef.current = null
     }
   }, [])