Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions messages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -348,5 +348,12 @@
"altLinkInstruction": "If the button above does not work, copy and paste this URL into your web browser:",
"ignoreNotice": "If you did not request a password reset, you can safely ignore this email. Your password will remain unchanged.",
"footerBrand": "Heliobond — Sunlight made financial."
},
"SessionTimeout": {
"title": "Your session will expire soon",
"body": "You have been inactive for a while. To protect your unsaved changes and account security, your session will automatically expire.",
"expiresIn": "Session expiring in",
"extendCta": "Stay connected",
"logoutCta": "Disconnect now"
}
}
7 changes: 7 additions & 0 deletions messages/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -348,5 +348,12 @@
"altLinkInstruction": "Si le bouton ci-dessus ne fonctionne pas, copiez et collez cette URL dans votre navigateur :",
"ignoreNotice": "Si vous n’avez pas demandé cette réinitialisation, vous pouvez ignorer cet e-mail en toute sécurité. Votre mot de passe restera inchangé.",
"footerBrand": "Heliobond — L’énergie solaire devenue finance."
},
"SessionTimeout": {
"title": "Votre session va bientôt expirer",
"body": "Vous êtes inactif depuis un moment. Pour protéger vos modifications non enregistrées et la sécurité de votre compte, votre session va expirer automatiquement.",
"expiresIn": "Expiration de la session dans",
"extendCta": "Rester connecté",
"logoutCta": "Se déconnecter"
}
}
36 changes: 33 additions & 3 deletions src/app/providers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,35 @@

import type { ReactNode } from 'react'
import { ThemeProvider } from '../theme/ThemeProvider'
import { WalletProvider } from '../wallet/WalletProvider'
import { ToastProvider } from '../components'
import { WalletProvider, useWallet } from '../wallet/WalletProvider'
import { ToastProvider, SessionTimeoutModal, useToast } from '../components'
import { useSessionTimeout } from '../hooks/useSessionTimeout'

function SessionWatcher() {
const { connected, disconnect } = useWallet()
const { toast } = useToast()

const { isWarningOpen, formattedRemaining, extendSession, expireNow } = useSessionTimeout({
enabled: connected,
onTimeout: () => {
disconnect()
toast({
tone: 'ember',
title: 'Session expired',
description: 'You have been disconnected due to inactivity.',
})
},
})

return (
<SessionTimeoutModal
open={isWarningOpen}
formattedTime={formattedRemaining}
onExtend={extendSession}
onLogout={expireNow}
/>
)
}

/**
* Client providers that must persist across route changes: theme (After Sunset
Expand All @@ -14,7 +41,10 @@ export function Providers({ children }: { children: ReactNode }) {
return (
<ThemeProvider>
<WalletProvider>
<ToastProvider>{children}</ToastProvider>
<ToastProvider>
<SessionWatcher />
{children}
</ToastProvider>
</WalletProvider>
</ThemeProvider>
)
Expand Down
81 changes: 81 additions & 0 deletions src/components/SessionTimeoutModal.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@/test/render'
import { SessionTimeoutModal } from './SessionTimeoutModal'

describe('SessionTimeoutModal', () => {
it('does not render when open is false', () => {
render(
<SessionTimeoutModal
open={false}
formattedTime="01:30"
onExtend={vi.fn()}
onLogout={vi.fn()}
/>,
)

expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
})

it('renders modal with title, message, formatted time, and action buttons when open is true', () => {
render(
<SessionTimeoutModal
open={true}
formattedTime="01:45"
onExtend={vi.fn()}
onLogout={vi.fn()}
/>,
)

const dialog = screen.getByRole('alertdialog')
expect(dialog).toBeInTheDocument()
expect(screen.getByText('Your session will expire soon')).toBeInTheDocument()
expect(screen.getByText('01:45')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Stay connected' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Disconnect now' })).toBeInTheDocument()
})

it('fires onExtend when Stay connected button is clicked', () => {
const onExtend = vi.fn()
render(
<SessionTimeoutModal
open={true}
formattedTime="01:45"
onExtend={onExtend}
onLogout={vi.fn()}
/>,
)

fireEvent.click(screen.getByRole('button', { name: 'Stay connected' }))
expect(onExtend).toHaveBeenCalledTimes(1)
})

it('fires onLogout when Disconnect now button is clicked', () => {
const onLogout = vi.fn()
render(
<SessionTimeoutModal
open={true}
formattedTime="01:45"
onExtend={vi.fn()}
onLogout={onLogout}
/>,
)

fireEvent.click(screen.getByRole('button', { name: 'Disconnect now' }))
expect(onLogout).toHaveBeenCalledTimes(1)
})

it('fires onExtend when Escape key is pressed to prevent accidental session drop', () => {
const onExtend = vi.fn()
render(
<SessionTimeoutModal
open={true}
formattedTime="01:45"
onExtend={onExtend}
onLogout={vi.fn()}
/>,
)

fireEvent.keyDown(window, { key: 'Escape' })
expect(onExtend).toHaveBeenCalledTimes(1)
})
})
234 changes: 234 additions & 0 deletions src/components/SessionTimeoutModal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,234 @@
'use client'

import { useEffect, useRef } from 'react'
import { useTranslations } from 'next-intl'
import { Button } from './Button'

export interface SessionTimeoutModalProps {
/** Whether the modal is currently visible. */
open: boolean
/** Formatted MM:SS time remaining string. */
formattedTime: string
/** Callback fired when user chooses to stay logged in. */
onExtend: () => void
/** Callback fired when user chooses to disconnect immediately. */
onLogout: () => void
}

/**
* Accessible alert dialog notifying users of an impending session timeout,
* giving them an opportunity to extend their session and prevent unsaved form data loss.
*/
export function SessionTimeoutModal({
open,
formattedTime,
onExtend,
onLogout,
}: SessionTimeoutModalProps) {
const t = useTranslations('SessionTimeout')
const extendBtnRef = useRef<HTMLButtonElement | null>(null)
const modalRef = useRef<HTMLDivElement | null>(null)

// Auto-focus the primary extend button when modal opens
useEffect(() => {
if (open) {
const prevActive = document.activeElement as HTMLElement | null
const timer = setTimeout(() => {
extendBtnRef.current?.focus()
}, 50)

return () => {
clearTimeout(timer)
prevActive?.focus()
}
}
}, [open])

// Trap focus & keyboard escape handler
useEffect(() => {
if (!open) return

const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
// Esc extends the session by default to prevent accidental data loss
onExtend()
}

if (e.key === 'Tab' && modalRef.current) {
const focusables = modalRef.current.querySelectorAll<HTMLElement>(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',
)
if (focusables.length === 0) return

const first = focusables[0]
const last = focusables[focusables.length - 1]

if (e.shiftKey && document.activeElement === first) {
e.preventDefault()
last.focus()
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault()
first.focus()
}
}
}

window.addEventListener('keydown', handleKeyDown)
return () => window.removeEventListener('keydown', handleKeyDown)
}, [open, onExtend])

if (!open) return null

return (
<div
style={{
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'rgba(11, 43, 35, 0.65)',
backdropFilter: 'blur(6px)',
WebkitBackdropFilter: 'blur(6px)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
zIndex: 9999,
padding: 20,
}}
>
<div
ref={modalRef}
role="alertdialog"
aria-modal="true"
aria-labelledby="session-timeout-title"
aria-describedby="session-timeout-desc"
style={{
background: 'var(--surface)',
border: '1px solid var(--ink-12)',
borderRadius: 'var(--radius-modal)',
boxShadow: 'var(--shadow-lg)',
maxWidth: 480,
width: '100%',
padding: '32px 28px 24px',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
textAlign: 'center',
animation: 'hb-rise 300ms var(--ease-out) forwards',
}}
>
{/* Animated Warning Icon */}
<div
style={{
width: 56,
height: 56,
borderRadius: '50%',
backgroundColor: 'var(--solar-12)',
border: '2px solid var(--solar)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: 24,
marginBottom: 20,
}}
aria-hidden="true"
>
</div>

<h2
id="session-timeout-title"
style={{
fontFamily: 'var(--font-display)',
fontSize: 'var(--type-h3-sm)',
fontWeight: 700,
color: 'var(--ink)',
margin: '0 0 10px',
letterSpacing: '-0.01em',
}}
>
{t('title')}
</h2>

<p
id="session-timeout-desc"
style={{
fontFamily: 'var(--font-body)',
fontSize: 'var(--type-body)',
lineHeight: 1.5,
color: 'var(--ink-60)',
margin: '0 0 20px',
}}
>
{t('body')}
</p>

{/* Live Countdown Display */}
<div
style={{
background: 'var(--ink-06)',
border: '1px solid var(--ink-12)',
borderRadius: 'var(--radius-card)',
padding: '12px 20px',
marginBottom: 24,
width: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<span
style={{
fontFamily: 'var(--font-body)',
fontSize: 'var(--type-small)',
color: 'var(--ink-60)',
fontWeight: 500,
}}
>
{t('expiresIn')}
</span>
<span
className="hb-data"
style={{
fontFamily: 'var(--font-data)',
fontSize: 'var(--type-body-lg)',
fontWeight: 700,
color: 'var(--ember)',
}}
>
{formattedTime}
</span>
</div>

{/* Action Buttons */}
<div
style={{
display: 'flex',
gap: 12,
width: '100%',
flexDirection: 'row',
}}
>
<Button
variant="secondary"
size="lg"
onClick={onLogout}
style={{ flex: 1 }}
>
{t('logoutCta')}
</Button>
<Button
ref={extendBtnRef}
variant="primary"
size="lg"
onClick={onExtend}
style={{ flex: 1 }}
>
{t('extendCta')}
</Button>
</div>
</div>
</div>
)
}
2 changes: 2 additions & 0 deletions src/components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,6 @@ export type {
} from './FormField'
export { Sparkline } from './Sparkline'
export type { SparklineProps } from './Sparkline'
export { SessionTimeoutModal } from './SessionTimeoutModal'
export type { SessionTimeoutModalProps } from './SessionTimeoutModal'
export * from './icons'
Loading
Loading