import './storageFallback'
import { StrictMode, useState, type FormEvent, type ReactNode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import './App.css'
import { LanguageProvider, useT } from './i18n'
import { discardVault, hasVault, unlockVault } from './vault'
import {
SYNC_CATEGORIES,
accountInfo,
formatAccountNumber,
loginSyncAccount,
normalizePassword,
pullAtStartup,
resolveConflict,
startAutoSync,
syncErrorKey,
takeSyncLink,
} from './sync'
const root = createRoot(document.getElementById('root')!)
// App reads its stored identities/favorites while loading, so it's imported only after the vault is open
// and the sync account (Options -> Konto) had its chance to bring in newer data.
async function start() {
const { default: App } = await import('./App.tsx')
startAutoSync()
root.render(
,
)
}
const dialog = (node: ReactNode) => root.render({node})
async function boot() {
const link = takeSyncLink()
if (link) return dialog()
// Don't hold the client hostage to a slow sync server.
const deadline = Date.now() + 5000
const result = await Promise.race([
pullAtStartup(deadline),
new Promise<'ok'>((resolve) => setTimeout(() => resolve('ok'), 5000)),
])
if (result === 'conflict') return dialog()
void start()
}
/** Opened through the QR code / link from Options -> Konto on another device. */
function SyncLinkDialog({ link }: { link: { number: string; password?: string; server: string } }) {
const t = useT()
const [password, setPassword] = useState(link.password ?? '')
const [askPassword, setAskPassword] = useState(false)
const [error, setError] = useState('')
const [busy, setBusy] = useState(false)
const submit = async (e: FormEvent) => {
e.preventDefault()
setBusy(true)
setError('')
try {
if (!password) {
const info = await accountInfo(link.number, link.server)
if (!info.exists) throw new Error('not_found')
if (info.hasPassword) {
setAskPassword(true)
setBusy(false)
return
}
}
await loginSyncAccount(link.number, password ? normalizePassword(password) : undefined, link.server, SYNC_CATEGORIES)
void start()
} catch (err) {
setError(t(syncErrorKey(err)))
setBusy(false)
}
}
return (
)
}
function SyncConflictDialog() {
const t = useT()
const [busy, setBusy] = useState(false)
const take = async (side: 'server' | 'local') => {
setBusy(true)
try {
await resolveConflict(side)
} finally {
void start()
}
}
return (
{t('sync.conflict.title')}
{t('sync.conflict.text')}
)
}
function Unlock() {
const t = useT()
const [password, setPassword] = useState('')
const [wrong, setWrong] = useState(false)
const [busy, setBusy] = useState(false)
const submit = async (e: FormEvent) => {
e.preventDefault()
setBusy(true)
if (await unlockVault(password)) return void boot()
setBusy(false)
setWrong(true)
}
return (
)
}
if (hasVault())
root.render(
,
)
else void boot()