| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482 |
- import {
- ChangeDetectionStrategy,
- Component,
- ElementRef,
- OnDestroy,
- computed,
- inject,
- signal,
- viewChild,
- } from '@angular/core';
- import { ActivatedRoute, Router } from '@angular/router';
- import { FmodeApi } from '../../../core/api/fmode-api';
- import { DeviceService } from '../../../core/device.service';
- import { PaletteService } from '../../../core/palette.service';
- import { SessionService } from '../../../core/session.service';
- type Stage = 'phone' | 'code' | 'token';
- /**
- * 移动端登录(Demo 02 + SPEC FR-02)—— **真实接口**
- *
- * 三步两路(与 Demo 一致):
- * 手机号 → 验证码 → 登录;或「使用 Token 直接登录」
- *
- * 与 Demo 的差异(Demo 是静态演示,只校验格式):
- * · 「获取验证码」真实调用 `FmodeApi.sendMobileCode`
- * · 「登录」真实调用 `loginWithMobile` / `loginWithToken`,成功后写 `SessionService`
- * · `?token=` / `#token=` 自动登录并清地址栏(AC-02.2),与桌面登录页同口径
- * · 发送验证码后 60s 倒计时,期间禁点(防重复下发)
- *
- * AC:02.3 redirect 回跳(replaceUrl)· 02.6 明确错误文案 · 02.7 提交期间防并发
- */
- @Component({
- selector: 'app-mb-login-page',
- changeDetection: ChangeDetectionStrategy.OnPush,
- template: `
- <div class="m-login">
- <div class="m-brand">
- <p class="m-wordmark">fmode</p>
- <h1>{{ stage() === 'token' ? 'Token 登录' : '欢迎使用' }}</h1>
- <p class="m-brand-sub">人机共生中枢 · 登录后继续</p>
- </div>
- @switch (stage()) {
- @case ('phone') {
- <label class="m-field">
- <span class="m-prefix">+86</span>
- <input
- #phoneEl
- type="tel"
- inputmode="numeric"
- maxlength="11"
- autocomplete="tel-national"
- placeholder="请输入手机号"
- [value]="phone()"
- aria-label="手机号"
- (input)="onPhone($event)"
- />
- </label>
- <button type="button" class="m-btn m-btn--primary" [disabled]="!phoneValid() || busy()" (click)="sendCode()">
- {{ sending() ? '发送中…' : '获取验证码' }}
- </button>
- <button type="button" class="m-more" (click)="stage.set('token')">使用 Token 直接登录</button>
- }
- @case ('code') {
- <label class="m-field">
- <span class="m-prefix">+86 {{ maskedPhone() }}</span>
- <input
- #codeEl
- type="tel"
- inputmode="numeric"
- maxlength="6"
- autocomplete="one-time-code"
- placeholder="6 位验证码"
- [value]="code()"
- aria-label="验证码"
- (input)="onCode($event)"
- />
- <button type="button" class="m-get" [disabled]="countdown() > 0 || sending()" (click)="sendCode()">
- {{ countdown() > 0 ? countdown() + 's' : '重新发送' }}
- </button>
- </label>
- <button type="button" class="m-btn m-btn--primary" [disabled]="code().length !== 6 || busy()" (click)="submit()">
- {{ busy() ? '登录中…' : '登录' }}
- </button>
- <button type="button" class="m-more" (click)="backToPhone()">返回修改手机号</button>
- }
- @default {
- <label class="m-field">
- <input
- #tokenEl
- type="text"
- autocomplete="off"
- placeholder="粘贴 r: 开头的访问 Token"
- [value]="token()"
- aria-label="访问 Token"
- (input)="onToken($event)"
- />
- </label>
- <button type="button" class="m-btn m-btn--primary" [disabled]="!token().trim() || busy()" (click)="submit()">
- {{ busy() ? '登录中…' : '登录' }}
- </button>
- <button type="button" class="m-more" (click)="stage.set('phone')">返回手机号登录</button>
- }
- }
- @if (error()) {
- <p class="m-error" role="alert">
- <i class="fa-solid fa-circle-exclamation" aria-hidden="true"></i>
- {{ error() }}
- </p>
- }
- <label class="m-agree">
- <button
- type="button"
- class="m-cb"
- [class.on]="agreed()"
- role="checkbox"
- [attr.aria-checked]="agreed()"
- aria-label="同意协议"
- (click)="agreed.set(!agreed())"
- >
- @if (agreed()) {
- <i class="fa-solid fa-check" aria-hidden="true"></i>
- }
- </button>
- <span>
- 已阅读并同意<a href="#" (click)="blockLink($event)">服务协议</a>和<a href="#" (click)="blockLink($event)">隐私政策</a>
- </span>
- </label>
- </div>
- `,
- styles: [
- `
- :host {
- display: block;
- min-height: 100dvh;
- background: var(--canvas);
- }
- .m-login {
- display: flex;
- flex-direction: column;
- min-height: 100dvh;
- box-sizing: border-box;
- padding: calc(var(--mob-safe-top) + var(--sp-6)) var(--sp-6)
- calc(var(--mob-safe-bottom) + var(--sp-6));
- overflow-y: auto;
- }
- .m-brand {
- display: flex;
- flex: 1;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- text-align: center;
- padding: var(--sp-8) 0 var(--sp-6);
- }
- .m-wordmark {
- margin: 0 0 var(--sp-2);
- color: var(--primary);
- font-size: var(--fs-42);
- font-weight: 700;
- letter-spacing: -0.02em;
- }
- .m-brand h1 {
- margin: var(--sp-3) 0 var(--sp-1);
- color: var(--ink);
- font-size: var(--fs-26);
- }
- .m-brand-sub {
- margin: 0;
- color: var(--muted);
- font-size: var(--fs-13);
- }
- .m-field {
- display: flex;
- align-items: center;
- gap: var(--sp-2);
- height: 52px;
- margin-bottom: var(--sp-3);
- padding: 0 var(--sp-4);
- box-sizing: border-box;
- border: 1px solid var(--edge);
- border-radius: var(--r-md);
- background: var(--surface);
- }
- .m-field input {
- flex: 1;
- min-width: 0;
- border: 0;
- outline: 0;
- background: transparent;
- color: var(--ink);
- font-size: var(--fs-17);
- }
- .m-prefix {
- flex: none;
- color: var(--ink-2);
- font-size: var(--fs-15);
- }
- .m-get {
- flex: none;
- border: 0;
- background: none;
- color: var(--primary);
- font: inherit;
- font-size: var(--fs-13);
- font-weight: 600;
- white-space: nowrap;
- cursor: pointer;
- }
- .m-get:disabled {
- color: var(--muted);
- cursor: not-allowed;
- }
- .m-btn {
- width: 100%;
- height: 52px;
- margin-bottom: var(--sp-3);
- border: 0;
- border-radius: var(--r-md);
- font: inherit;
- font-size: var(--fs-17);
- font-weight: 600;
- cursor: pointer;
- }
- .m-btn--primary {
- background: var(--primary);
- color: var(--primary-content);
- }
- .m-btn:disabled {
- opacity: 0.5;
- cursor: not-allowed;
- }
- .m-more {
- padding: var(--sp-3) 0;
- border: 0;
- background: none;
- color: var(--primary);
- font: inherit;
- font-size: var(--fs-13);
- cursor: pointer;
- }
- .m-error {
- display: flex;
- align-items: center;
- gap: var(--sp-2);
- margin: 0 0 var(--sp-3);
- padding: var(--sp-3);
- border-radius: var(--r-md);
- background: var(--danger-subtle);
- color: var(--danger);
- font-size: var(--fs-13);
- }
- .m-agree {
- display: flex;
- align-items: flex-start;
- justify-content: center;
- gap: var(--sp-2);
- margin-top: var(--sp-4);
- color: var(--muted);
- font-size: var(--fs-12);
- text-align: left;
- }
- .m-agree a {
- color: var(--primary);
- text-decoration: none;
- }
- .m-cb {
- display: grid;
- place-items: center;
- flex: none;
- width: 16px;
- height: 16px;
- margin-top: 2px;
- padding: 0;
- border: 1.5px solid var(--edge-strong);
- border-radius: var(--r-tag);
- background: none;
- color: var(--primary-content);
- font-size: var(--fs-9);
- cursor: pointer;
- }
- .m-cb.on {
- border-color: var(--primary);
- background: var(--primary);
- }
- `,
- ],
- })
- export class MbLoginPage implements OnDestroy {
- private readonly api = inject(FmodeApi);
- private readonly session = inject(SessionService);
- private readonly device = inject(DeviceService);
- private readonly palette = inject(PaletteService);
- private readonly router = inject(Router);
- private readonly route = inject(ActivatedRoute);
- protected readonly stage = signal<Stage>('phone');
- protected readonly phone = signal('');
- protected readonly code = signal('');
- protected readonly token = signal('');
- protected readonly agreed = signal(false);
- protected readonly error = signal<string | null>(null);
- protected readonly busy = signal(false);
- protected readonly sending = signal(false);
- protected readonly countdown = signal(0);
- protected readonly phoneValid = computed(() => /^1\d{10}$/.test(this.phone()));
- protected readonly maskedPhone = computed(() => {
- const p = this.phone();
- return `${p.slice(0, 3)}****${p.slice(7)}`;
- });
- private readonly phoneEl = viewChild<ElementRef<HTMLInputElement>>('phoneEl');
- private readonly codeEl = viewChild<ElementRef<HTMLInputElement>>('codeEl');
- private codeTimer: ReturnType<typeof setInterval> | null = null;
- constructor() {
- this.palette.init();
- void this.initFromUrl();
- }
- ngOnDestroy(): void {
- if (this.codeTimer) clearInterval(this.codeTimer);
- }
- protected onPhone(e: Event): void {
- const v = (e.target as HTMLInputElement).value.replace(/\D/g, '').slice(0, 11);
- this.phone.set(v);
- (e.target as HTMLInputElement).value = v;
- this.error.set(null);
- }
- protected onCode(e: Event): void {
- const v = (e.target as HTMLInputElement).value.replace(/\D/g, '').slice(0, 6);
- this.code.set(v);
- (e.target as HTMLInputElement).value = v;
- this.error.set(null);
- }
- protected onToken(e: Event): void {
- this.token.set((e.target as HTMLInputElement).value);
- this.error.set(null);
- }
- protected backToPhone(): void {
- this.stage.set('phone');
- this.code.set('');
- this.error.set(null);
- this.focus(this.phoneEl());
- }
- /** 发送验证码:真实接口 + 60s 倒计时(Demo 无倒计时,此处按规范补齐防刷) */
- protected async sendCode(): Promise<void> {
- if (this.sending() || this.countdown() > 0 || this.busy()) return;
- this.error.set(null);
- if (!this.phoneValid()) {
- this.error.set('请输入正确的 11 位手机号');
- return;
- }
- this.sending.set(true);
- try {
- await this.api.sendMobileCode(this.phone());
- this.stage.set('code');
- this.startCountdown();
- this.focus(this.codeEl());
- } catch (e) {
- this.error.set(this.messageOf(e));
- } finally {
- this.sending.set(false);
- }
- }
- protected async submit(): Promise<void> {
- if (this.busy()) return;
- this.error.set(null);
- if (this.stage() === 'code' && this.code().length !== 6) {
- this.error.set('请输入 6 位验证码');
- return;
- }
- if (this.stage() === 'token' && !this.token().trim()) {
- this.error.set('请输入访问令牌');
- return;
- }
- if (!this.agreed()) {
- this.error.set('请先阅读并同意服务协议和隐私政策');
- return;
- }
- this.busy.set(true);
- try {
- const s =
- this.stage() === 'token'
- ? await this.api.loginWithToken(this.token().trim())
- : await this.api.loginWithMobile(this.phone(), this.code());
- this.session.setSession(s.token, s.me);
- this.clearTokenFromAddress();
- await this.afterLogin();
- } catch (e) {
- this.error.set(this.messageOf(e));
- } finally {
- this.busy.set(false);
- }
- }
- /** 协议链接:当前无独立协议页,阻止默认跳转而不伪造内容 */
- protected blockLink(e: Event): void {
- e.preventDefault();
- }
- private startCountdown(): void {
- this.countdown.set(60);
- if (this.codeTimer) clearInterval(this.codeTimer);
- this.codeTimer = setInterval(() => {
- const next = this.countdown() - 1;
- this.countdown.set(next);
- if (next <= 0 && this.codeTimer) {
- clearInterval(this.codeTimer);
- this.codeTimer = null;
- }
- }, 1000);
- }
- private focus(el: ElementRef<HTMLInputElement> | undefined): void {
- // 等下一帧再聚焦:当前 DOM 可能刚因 stage 切换重建
- setTimeout(() => el?.nativeElement.focus(), 0);
- }
- /** 已登录直接进入(地址带 token 时仍走 initFromUrl,可能要换身份) */
- private redirectIfLoggedIn(): boolean {
- const urlToken = this.route.snapshot.queryParamMap.get('token');
- if (this.session.isLoggedIn() && !urlToken) {
- void this.afterLogin();
- return true;
- }
- return false;
- }
- /** AC-02.2:`?token=` / `#token=` 自动登录并清地址栏 */
- private async initFromUrl(): Promise<void> {
- if (this.redirectIfLoggedIn()) return;
- const hash = typeof location !== 'undefined' ? location.hash : '';
- const query = this.route.snapshot.queryParamMap;
- const urlToken = query.get('token') ?? /^#token=(.+)$/.exec(hash)?.[1] ?? '';
- if (!urlToken) return;
- this.busy.set(true);
- this.agreed.set(true);
- try {
- const s = await this.api.loginWithToken(decodeURIComponent(urlToken));
- this.session.setSession(s.token, s.me);
- this.clearTokenFromAddress();
- await this.afterLogin();
- } catch (e) {
- this.error.set(this.messageOf(e));
- } finally {
- this.busy.set(false);
- }
- }
- private clearTokenFromAddress(): void {
- if (typeof history === 'undefined') return;
- const url = new URL(location.href);
- url.hash = '';
- url.searchParams.delete('token');
- history.replaceState({}, '', url.toString());
- }
- /** AC-02.3:按 redirect 回跳,且 replaceUrl */
- private async afterLogin(): Promise<void> {
- const redirect = this.route.snapshot.queryParamMap.get('redirect');
- const target = redirect && redirect.startsWith('/') ? redirect : '/mobile/messages';
- await this.router.navigateByUrl(this.device.normalize(target), { replaceUrl: true });
- }
- private messageOf(e: unknown): string {
- return e instanceof Error && e.message ? e.message : '登录失败,请稍后重试';
- }
- }
|