Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
import { useState } from 'react'
import { ChevronDown, Server, CheckCircle2, AlertTriangle, Loader } from 'lucide-react'
import {
useServerStore,
normalizeServerUrl,
isInsecureServerUrl,
isMixedContentBlocked,
} from '../stores/server'
import { Trans, useTranslation, uiMessage, type UiMessage } from '@lyftr/shared'
import { testServerConnection } from '../services/api'
type Status =
| { kind: 'idle' }
| { kind: 'testing' }
| { kind: 'ok'; name: string; version: string }
| { kind: 'warn'; failure: UiMessage }
| { kind: 'error'; key: 'server.status.invalidUrlExample' | 'server.status.storageBlocked' }
// Bitwarden-style server selector shared by Login and Register: validates and
// normalizes the URL, tests connectivity against the backend's public /info, and
// saves regardless of the result (a server may be temporarily down) while showing
// clear status. Empty means "use this site's own origin via the reverse proxy".
export default function ServerSettings() {
const { t } = useTranslation()
const { serverUrl, setServerUrl } = useServerStore()
const [open, setOpen] = useState(false)
const [input, setInput] = useState(serverUrl)
const [status, setStatus] = useState<Status>({ kind: 'idle' })
// Blocked wins over insecure: both are true for http-from-https, but one is a hard
// failure the user must fix and the other is a risk they may knowingly accept.
const blocked = isMixedContentBlocked(serverUrl)
const insecure = !blocked && isInsecureServerUrl(serverUrl)
const handleSave = async () => {
const raw = input.trim()
const normalized = normalizeServerUrl(raw) // '' = same origin (reverse proxy)
if (raw && !normalized) {
setStatus({ kind: 'error', key: 'server.status.invalidUrlExample' })
return
}
// Save immediately (warn-but-save): the choice is authoritative right away;
// the connection probe below is advisory and may lag on a slow/down server.
//
// Awaited: the store persists through an async storage adapter, so firing this and
// moving on would report "Connected" for a write that had not landed — or failed
// outright (quota, Safari private mode) — leaving the old server in effect on the
// next load while the user was told otherwise.
try {
await setServerUrl(normalized)
} catch {
setStatus({ kind: 'error', key: 'server.status.storageBlocked' })
return
}
setInput(normalized)
setStatus({ kind: 'testing' })
const result = await testServerConnection(normalized)
setStatus(
result.ok
? { kind: 'ok', name: result.info.name, version: result.info.version }
: { kind: 'warn', failure: result.failure },
)
}
return (
<div className="mb-4">
<button
type="button"
onClick={() => setOpen(o => !o)}
className="flex items-center gap-2 px-3 py-2 w-full text-xs text-tx-muted hover:text-tx-secondary rounded-lg hover:bg-surface-muted/40 transition-colors"
>
<Server className="w-3.5 h-3.5" />
<span>{t('server.settingsTitle')}</span>
{/* Stays visible while the panel is collapsed — the problem outlives the moment of entry. */}
{blocked && (
<span className="flex items-center gap-1 text-error-400" title={t('server.mixedContentWarning')}>
<AlertTriangle className="w-3 h-3" />
{t('server.blocked')}
</span>
)}
{insecure && (
<span className="flex items-center gap-1 text-warning-400" title={t('server.insecureWarning')}>
<AlertTriangle className="w-3 h-3" />
{t('server.notEncrypted')}
</span>
)}
<ChevronDown className={`w-3 h-3 ml-auto transition-transform ${open ? 'rotate-180' : ''}`} />
</button>
{open && (
<div className="mt-2 p-3 bg-surface-muted/30 border border-surface-border rounded-lg space-y-2">
<label className="block text-xs font-medium text-tx-secondary uppercase tracking-wider">{t('settings.server.url.label')}</label>
<input
type="text"
value={input}
onChange={e => { setInput(e.target.value); setStatus({ kind: 'idle' }) }}
placeholder={t('server.blankPlaceholder')}
className="input text-sm"
autoComplete="off"
autoCapitalize="off"
spellCheck={false}
/>
<p className="text-[11px] leading-relaxed text-tx-muted">
<Trans
i18nKey="server.fullUrlHint"
components={{ url: <span className="font-mono text-tx-secondary" /> }}
/>
</p>
{blocked && (
<p className="flex items-start gap-1.5 text-xs text-error-400">
<AlertTriangle className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" />
<span>{t('server.mixedContentWarning')}</span>
</p>
)}
{insecure && (
<p className="flex items-start gap-1.5 text-xs text-warning-400">
<AlertTriangle className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" />
<span>{t('server.insecureWarning')}</span>
</p>
)}
{status.kind === 'error' && <p className="text-xs text-error-400">{t(status.key)}</p>}
{status.kind === 'warn' && (
<p className="flex items-start gap-1.5 text-xs text-warning-400">
<AlertTriangle className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" />
<span>{t('settings.server.savedWithWarning', { message: uiMessage(status.failure) })}</span>
</p>
)}
{status.kind === 'ok' && (
<p className="flex items-center gap-1.5 text-xs text-success-500">
<CheckCircle2 className="w-3.5 h-3.5 flex-shrink-0" />
<span>{t('server.status.connected', { name: status.name, version: status.version })}</span>
</p>
)}
<div className="flex gap-2 pt-1">
<button
type="button"
onClick={handleSave}
disabled={status.kind === 'testing'}
className="flex-1 px-2 py-1.5 text-xs bg-brand-500 hover:bg-brand-600 disabled:opacity-40 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-1.5"
>
{status.kind === 'testing'
? (<><Loader className="w-3.5 h-3.5 animate-spin" /> {t('server.testing')}</>)
: t('server.testAndSave')}
</button>
<button
type="button"
onClick={() => setOpen(false)}
className="flex-1 px-2 py-1.5 text-xs bg-surface-border text-tx-secondary hover:bg-surface-border/80 rounded-lg transition-colors"
>
{t('common.close')}
</button>
</div>
<p className="text-xs text-tx-muted pt-1">
{serverUrl ? t('server.current', { url: serverUrl }) : t('server.usingSite')}
</p>
</div>
)}
</div>
)
}