feat(web): add backend switcher and connection status

Split the login page into backend list and credentials, show connection status in the sidebar and top bar, and render dialogs in a portal.
This commit is contained in:
justme committed 2026-10-06 16:59:17 +08:00
1 parent 91c63d0cf2
commit a9538eae4a
13 files changed
+522 -100

No files matched your search

+145 -36
View File
@@ -1,8 +1,9 @@
import { Check, Copy, Moon, Plug, Sun } from 'lucide-react'
import { Check, Copy, Moon, Plug, Plus, Sun, X } from 'lucide-react'
import { createPortal } from 'react-dom'
import { Component, createContext, useCallback, useContext, useEffect, useRef, useState, type ErrorInfo, type ReactNode } from 'react'
import { ApiError } from '../api/client'
import { getBase, getToken, normalizeBase, setSource } from '../api/source'
import { useTheme } from '../hooks'
import { ApiError, loginTo } from '../api/client'
import { activateSource, getBase, listSources, normalizeBase, pingBackend, removeSource, setSource } from '../api/source'
import { useQuery, useTheme } from '../hooks'
import { translateCode, translateField, translateMessage } from '../i18n'
/** 连接式分组(单选):组内小圆角、外角大圆角,选中段变胶囊。 */
@@ -64,14 +65,17 @@ export function Dialog({ title, onClose, children, actions }: { title: string; o
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose])
return (
// 渲染到 body 上:对话框是 position: fixed 的,如果放在带 backdrop-filter / transform 的祖先里(比如展示端的顶栏),
// 它会以那个祖先为定位基准,被挤到顶栏里、一半在屏幕外
return createPortal(
<div className="scrim" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="dialog" role="dialog" aria-modal="true" aria-label={title}>
<h2>{title}</h2>
{children}
{actions ? <div className="actions">{actions}</div> : null}
</div>
</div>
</div>,
document.body,
)
}
@@ -340,49 +344,154 @@ export class ErrorBoundary extends Component<{ children: ReactNode }, { error: E
}
}
/** 数据源设置:默认连同源的后端;填了地址就连别的后端(跨域用 API 令牌,后端要放行这个前端的来源)。 */
export function SourceButton({ tokenLabel = '只读令牌(站点私有时才需要)' }: { tokenLabel?: string }) {
/** 地址的简短写法:去掉协议,留 host(和端口)。 */
const shortHost = (base: string) => base.replace(/^https?:\/\//i, '')
/**
* 数据源:默认连这个页面所在的后端(同源);也可以保存几个别的后端(比如本机跑前端、连线上的),在列表里点一下就切换。
* 跨域时不用 Cookie,改用 API 令牌,所以每个后端各存一个令牌(只在浏览器里),后端需要放行这个页面的来源(`Monitor__CorsOrigins`)。
*/
export function SourceButton({ variant = 'icon' }: { variant?: 'icon' | 'status' }) {
const [open, setOpen] = useState(false)
const [adding, setAdding] = useState(listSources().length === 0)
const [base, setBase] = useState('')
const [token, setToken] = useState('')
const remote = getBase() !== ''
const show = () => {
setBase(getBase())
setToken(getToken())
setOpen(true)
}
const apply = (nextBase: string, nextToken: string) => {
setSource(nextBase, nextToken)
location.reload()
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const [busy, setBusy] = useState(false)
const [, refresh] = useState(0)
const active = getBase()
const saved = listSources()
const switchTo = (next: string) => {
if (next !== active) {
activateSource(next)
location.reload()
}
}
// 状态条用:每 15 秒问一下当前后端还连不连得上
const health = useQuery(() => (variant === 'status' ? pingBackend() : Promise.resolve(undefined)), [variant, active], variant === 'status' ? 15_000 : undefined)
const state = health.data === false ? 'bad' : health.data === undefined ? 'wait' : 'ok'
const rows = saved.map((x) => ({ base: x.base, label: shortHost(x.base), detail: x.token ? '已登录' : '未登录' }))
// 连接中的排在最前面
rows.sort((a, b) => Number(b.base === active) - Number(a.base === active))
return (
<>
<button type="button" className={`btn icon${remote ? ' primary' : ''}`} onClick={show} aria-label="数据源" title={remote ? `数据源:${getBase()}` : '数据源:同源'}>
<Plug size={18} />
</button>
{variant === 'status' ? (
<button type="button" className={`src-status ${state}`} onClick={() => setOpen(true)} aria-label="数据源" title={`后端:${active || location.origin}(点击切换)`}>
<span className="st-dot" />
<span className="st-host">{shortHost(active || location.origin)}</span>
<span className="st">{state === 'ok' ? '已连接' : state === 'bad' ? '无法连接' : '连接中…'}</span>
</button>
) : (
<button type="button" className={`btn icon${active ? ' primary' : ''}`} onClick={() => setOpen(true)} aria-label="数据源" title={active ? `后端:${active}` : `后端:${location.origin}`}>
<Plug size={18} />
</button>
)}
{open ? (
<Dialog
title="数据源"
onClose={() => setOpen(false)}
actions={
<>
<button type="button" className="btn" onClick={() => apply('', '')}>
恢复同源
</button>
<button type="button" className="btn primary" onClick={() => apply(base, token)}>
保存并刷新
</button>
</>
<button type="button" className="btn" onClick={() => setOpen(false)}>
关闭
</button>
}
>
<div className="stack">
<p className="muted">默认连这个页面所在的后端。填了地址就连另一个后端(比如本机跑前端、连线上的);此时不用 Cookie,改用 API 令牌,后端需要放行这个页面的来源(<code>Monitor__CorsOrigins</code>)。</p>
<Field label="后端地址" hint={base && normalizeBase(base) !== base.trim() ? `将使用 ${normalizeBase(base)}` : '例如 https://mo.oeo.one;留空 = 同源'}>
<input className="input" value={base} onChange={(e) => setBase(e.target.value)} placeholder="https://mo.oeo.one" autoFocus />
</Field>
<Field label={tokenLabel}>
<input className="input" type="password" value={token} onChange={(e) => setToken(e.target.value)} autoComplete="off" />
</Field>
{rows.length > 0 ? (
<div className="src-list" role="listbox" aria-label="已保存的后端">
{rows.map((row) => {
const on = row.base === active
return (
<div key={row.base || 'same-origin'} className={`src-row${on ? ' on' : ''}`}>
<button type="button" role="option" aria-selected={on} className="src-pick" onClick={() => switchTo(row.base)} title={on ? '正在连接' : '点击切换到这个后端'}>
<span className="src-dot" />
<span className="src-text">
<b>{row.label}</b>
<small>{row.detail}</small>
</span>
{on ? <span className="chip accent">连接中</span> : null}
</button>
{row.base ? (
<button
type="button"
className="btn icon small"
aria-label="忘掉这个后端"
title={on ? '断开并忘掉这个后端' : '忘掉这个后端'}
onClick={() => {
removeSource(row.base)
if (on) location.reload()
else refresh((n) => n + 1)
}}
>
<X size={14} />
</button>
) : null}
</div>
)
})}
</div>
) : (
<p className="muted">还没有保存后端。填上后端地址和用户名、密码,就可以连上去;不填则使用 {location.origin} 的 API。</p>
)}
{adding ? (
<div className="stack">
<Field label="后端地址" hint={base && normalizeBase(base) !== base.trim() ? `将使用 ${normalizeBase(base)}` : '例如 https://mo.oeo.one'}>
<input className="input" name="backend-url" type="url" autoComplete="url" value={base} onChange={(e) => setBase(e.target.value)} placeholder="https://mo.oeo.one" autoFocus />
</Field>
<Field label="用户名" hint="站点公开、只想看数据的话可以留空">
<input className="input" name="backend-username" autoComplete="off" value={username} onChange={(e) => setUsername(e.target.value)} />
</Field>
<Field label="密码">
<input className="input" name="backend-password" type="password" autoComplete="new-password" value={password} onChange={(e) => setPassword(e.target.value)} />
</Field>
{error ? <div className="notice bad">{error}</div> : null}
<div className="row" style={{ gap: 8 }}>
<button
type="button"
className="btn primary"
disabled={!normalizeBase(base) || busy}
onClick={async () => {
setBusy(true)
setError('')
try {
// 填了用户名就先登录(拿回会话存起来),登录成功才保存这个后端
setSource(base, username ? await loginTo(normalizeBase(base), username, password) : '')
location.reload()
} catch (err) {
setError(describeError(err))
} finally {
setBusy(false)
}
}}
>
保存并连接
</button>
{rows.length > 0 ? (
<button type="button" className="btn" onClick={() => setAdding(false)}>
取消
</button>
) : null}
</div>
</div>
) : (
<div>
<button
type="button"
className="btn small"
onClick={() => {
setBase('')
setUsername('')
setPassword('')
setError('')
setAdding(true)
}}
>
<Plus size={14} />
添加后端
</button>
</div>
)}
</div>
</Dialog>
) : null}