添加登录功能

This commit is contained in:
zpx committed 2026-11-20 15:13:11 +08:00
commit a3f61a29d0
120 files changed
+3974

No files matched your search

@@ -0,0 +1,53 @@
import { GuestError, GuestLogin, GuestSession } from './GuestContracts';
export type LoginPhase = 'idle' | 'signing-in' | 'authenticated' | 'failed';
export interface LoginState { phase: LoginPhase; message: string; enabled: boolean }
export interface LoginViewPort { render(state: LoginState): void }
/** 独立于引擎的交互状态机,方便测试连点与销毁。 / Engine-independent interaction state machine for repeated-click and lifecycle tests. */
export class GuestLoginPresenter {
private operation: AbortController | null = null;
private disposed = false;
private authenticated = false;
constructor(private readonly view: LoginViewPort, private readonly service: () => GuestLogin,
private readonly completed: (session: GuestSession) => void) {}
async submit(): Promise<void> {
if (this.disposed || this.operation || this.authenticated) return;
if (typeof AbortController === 'undefined') {
this.view.render({ phase: 'failed', message: 'Secure sign-in is unavailable on this platform.', enabled: true });
return;
}
const operation = new AbortController();
this.operation = operation;
let authenticated: GuestSession | null = null;
try {
this.view.render({ phase: 'signing-in', message: 'Signing in...', enabled: false });
const session = await this.service().signIn(operation.signal);
if (!this.isCurrent(operation)) return;
this.authenticated = true;
authenticated = session;
} catch (error) {
if (!this.isCurrent(operation)) return;
const message = error instanceof GuestError ? error.message : 'Unable to sign in. Please retry.';
this.view.render({ phase: 'failed', message, enabled: true });
} finally {
if (this.operation === operation) this.operation = null;
}
if (authenticated) {
// 成功通知异常不能回滚已保存的认证状态。 / Presentation failures must not turn committed authentication into a login failure.
try {
this.view.render({ phase: 'authenticated', message: 'Signed in successfully.', enabled: false });
this.completed(authenticated);
} catch { /* 保留已认证状态且不输出会话。 / Retain authentication without logging the session. */ }
}
}
cancel(): void {
const operation = this.operation;
this.operation = null;
operation?.abort();
if (!this.disposed && !this.authenticated) this.view.render({ phase: 'idle', message: '', enabled: true });
}
dispose(): void { this.disposed = true; this.cancel(); }
private isCurrent(operation: AbortController): boolean {
return !this.disposed && this.operation === operation && !operation.signal.aborted;
}
}