Skip to content

Extract countdown & tab close logic to custom hook #35

Description

@vertefra

Problem

Countdown and tab close logic is duplicated across 4 view files with identical implementation:

  • views/SleepOnIt.tsx (lines 110-138)
  • views/IDontNeedIt.tsx (lines 42-76)
  • views/EarlyReturnFromSleep.tsx (lines 66-93)
  • views/BackToAnOldFlame.tsx (lines 63-90)

Solution

Create a reusable custom hook:

// hooks/useCountdownAndClose.ts
export const useCountdownAndClose = (
  onClose?: () => void
) => {
  const [countdown, setCountdown] = useState<number | null>(null)
  
  useEffect(() => {
    if (countdown === null) return
    
    if (countdown === 0) {
      const closeTab = async () => {
        console.log("Requesting tab close...")
        try {
          await ChromeMessaging.closeCurrentTab()
          console.log("Tab close successful")
        } catch (error) {
          console.error("Tab close failed:", error)
          if (onClose) onClose()
        }
      }
      closeTab()
      return
    }
    
    const timer = setTimeout(() => {
      setCountdown(countdown - 1)
    }, 1000)
    
    return () => clearTimeout(timer)
  }, [countdown, onClose])
  
  return { 
    countdown, 
    startCountdown: (seconds: number) => setCountdown(seconds) 
  }
}

Impact

  • Reduces code duplication by ~100 lines
  • Improves maintainability
  • Ensures consistent behavior across views

Priority

High

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions