浏览代码

fix(learning): speed up word playback and improve held swipe meanings

彭峰 1 小时之前
父节点
当前提交
1d99ed2ff2

+ 32 - 4
projects/xiaoshu-mobile/src/app/core/all-routes.integration.spec.ts

@@ -1,9 +1,9 @@
 import { signal } from '@angular/core';
 import { provideHttpClient } from '@angular/common/http';
 import { TestBed } from '@angular/core/testing';
-import { provideRouter, Router } from '@angular/router';
+import { NavigationEnd, provideRouter, Router } from '@angular/router';
 import { RouterTestingHarness } from '@angular/router/testing';
-import { Observable, of } from 'rxjs';
+import { filter, firstValueFrom, Observable, of, take } from 'rxjs';
 import { routes } from '../app.routes';
 import { ApiService } from './api.service';
 import { BytedeskChatSession, BytedeskMessage, BytedeskService } from './bytedesk.service';
@@ -53,6 +53,7 @@ describe('all migrated routes', () => {
   };
 
   beforeEach(() => {
+    fakeSession.isLoggedIn.set(true);
     for (const storage of [localStorage, sessionStorage]) for (const key of Object.keys(storage)) if (key.startsWith('xiaoshu.learning.')) storage.removeItem(key);
     TestBed.configureTestingModule({
       providers: [
@@ -75,8 +76,35 @@ describe('all migrated routes', () => {
     for (const page of PAGE_CATALOG) {
       await harness.navigateByUrl(`/${page.path}`);
       const studentRedirect = page.path === 'pages/stu/index' || coachOnlyRoutes.has(page.path);
-      expect(router.url.split(/[?#]/, 1)[0]).withContext(page.path).toBe(studentRedirect ? '/pages/home/cart' : `/${page.path}`);
-      expect(document.title).withContext(page.path).toContain(studentRedirect ? '伴学中心' : page.title);
+      const destination = page.kind === 'login' ? '/pages/home/index' : studentRedirect ? '/pages/home/cart' : `/${page.path}`;
+      const title = page.kind === 'login' ? '小树陪练' : studentRedirect ? '伴学中心' : page.title;
+      expect(router.url.split(/[?#]/, 1)[0]).withContext(page.path).toBe(destination);
+      expect(document.title).withContext(page.path).toContain(title);
     }
   });
+  it('shows the login form when the WeChat link has no restored session', async () => {
+    fakeSession.isLoggedIn.set(false);
+    const harness = await RouterTestingHarness.create('/pages/member/wxauth');
+    expect(TestBed.inject(Router).url).toBe('/pages/member/wxauth');
+    expect(document.title).toContain('登录系统');
+    expect(harness.routeNativeElement?.querySelector('app-login-page')).not.toBeNull();
+  });
+
+  for (const [returnUrl, destination] of [
+    ['/pages/home/cart', '/pages/home/cart'],
+    ['//example.com', '/pages/home/index'],
+    ['https://example.com', '/pages/home/index'],
+  ]) {
+    it(`restores the WeChat login destination for ${returnUrl}`, async () => {
+      const router = TestBed.inject(Router);
+      const arrived = firstValueFrom(router.events.pipe(
+        filter(event => event instanceof NavigationEnd && event.urlAfterRedirects === destination),
+        take(1),
+      ));
+      await RouterTestingHarness.create('/pages/member/wxauth?returnUrl=' + encodeURIComponent(returnUrl));
+      await arrived;
+      expect(TestBed.inject(Router).url).toBe(destination);
+    });
+  }
+
 });

+ 21 - 3
projects/xiaoshu-mobile/src/app/core/home-learning-modules.integration.spec.ts

@@ -1159,7 +1159,7 @@ describe('home learning modules', () => {
       const harness=await RouterTestingHarness.create('/pages/member/starshop');await harness.fixture.whenStable();harness.fixture.detectChanges();
       const component=harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
       const rows=()=>harness.routeNativeElement!.querySelectorAll<HTMLButtonElement>('.word-select-list > button');
-      const meanings=()=>Array.from(harness.routeNativeElement!.querySelectorAll('.word-select-list small'),node=>node.textContent);
+      const meanings=()=>Array.from(harness.routeNativeElement!.querySelectorAll('.word-select-list small.revealed'),node=>node.textContent);
       expect(meanings()).toEqual([]);
       rows()[0].click();await harness.fixture.whenStable();harness.fixture.detectChanges();expect(meanings()).toEqual([]);
       const old=play.calls.mostRecent().args[2]!;expect(old).toBeDefined();if(!old)return;
@@ -1183,7 +1183,7 @@ describe('home learning modules', () => {
       ? of({ retcode: 1, result: [{ GeneralID: 601, xxcs: 1, detail: [{ GeneralID: 701, Title: 'tend', yp: 'UploadFiles/tend.mp3' }] }],
         page: { itemCount: 1, pageCount: 1, pageIndex: 1, pageSize: Number(params?.['psize']) } } as ApiEnvelope<any>)
       : get(action, params));
-    const play = spyOn(TestBed.inject(PlatformService), 'play');
+    const play = spyOn(TestBed.inject(PlatformService), 'play').and.resolveTo('played');
     const harness = await RouterTestingHarness.create();
     await harness.navigateByUrl('/pages/member/starshop');
     harness.fixture.detectChanges();
@@ -1194,7 +1194,12 @@ describe('home learning modules', () => {
     expect(play).toHaveBeenCalledTimes(1);
     expect(play.calls.mostRecent().args[0]).toBe('UploadFiles/tend.mp3');
     expect(play.calls.mostRecent().args[0]).not.toContain('UploadFiles/UploadFiles');
-    (row.querySelector('.audio') as HTMLElement).click();
+    const speaker = row.querySelector<HTMLElement>('.audio')!;
+    speaker.click();
+    expect(play).toHaveBeenCalledTimes(1);
+    await harness.fixture.whenStable();
+    play.calls.mostRecent().args[2]!.onEnded();
+    speaker.click();
     harness.fixture.detectChanges();
     expect(play).toHaveBeenCalledTimes(2);
     expect(row.classList.contains('selected')).toBeTrue();
@@ -1350,6 +1355,19 @@ describe('home learning modules', () => {
     expect(localStorage.getItem(prefix + 'learn_mode')).toBeNull();
   }, 15000);
 
+  it('prepares existing course pronunciations as soon as the teacher sees the list', async () => {
+    user.set({userId:300,groupId:3});
+    session.groupId.set(3);
+    session.student.set({userId:100,groupId:1});
+    const platform = TestBed.inject(PlatformService);
+    const preload = spyOn(platform, 'preloadAudio');
+    const play = spyOn(platform, 'play');
+    const harness = await RouterTestingHarness.create('/pages/stu/stu_abc?nids=811&pnid=801');
+    await harness.fixture.whenStable();
+    expect(preload).toHaveBeenCalledWith(['UploadFiles/banana.mp3']);
+    expect(play).not.toHaveBeenCalled();
+  });
+
   for(const pass of [0,1,2,3]) {
     it(`waits for course word audio before revealing meanings in pass ${pass}`,async()=>{
       const {harness,component}=await teacherSelection(2,pass,'901');

+ 91 - 0
projects/xiaoshu-mobile/src/app/core/word-audio.service.spec.ts

@@ -71,6 +71,97 @@ describe('学习页面自动读音', () => {
     await component.play(word('101', 'apple.mp3'));
     expect(audio.ensure).not.toHaveBeenCalled(); expect(platform.play).toHaveBeenCalledTimes(1);
   });
+  it('学习页从选词草稿恢复补好的读音和已有释义,首次点读直接播放', async () => {
+    component.meta.path = 'pages/stu/stu_con';
+    const item = (component as any).toWord({GeneralID: 101, yp: 'old.mp3', audio: '/prepared.mp3', sy: ' ', detail: {sy: '苹果'}});
+    await component.play(item);
+    expect(platform.play.calls.first().args[0]).toBe('/prepared.mp3');
+    expect(item.meaning).toBe('苹果');
+    expect(audio.ensure).not.toHaveBeenCalled();
+  });
+
+  it('跟读时同一词缓冲中连点只启动一次,已出声后下一次点读可以重播', fakeAsync(() => {
+    component.meta.path = 'pages/stu/stu_con';
+    const item = word('101', '/apple.mp3');
+    component.words.set([item, word('102', '/pear.mp3')]);
+    let start!: () => void;
+    platform.play.and.returnValue(new Promise<void>(done => start = done).then(() => 'played'));
+    component.repeatWord(item, 0);
+    component.repeatWord(item, 0);
+    expect(platform.play).toHaveBeenCalledTimes(1);
+    expect(component.repetitions()[item.id]).toBe(2);
+    start();
+    flushMicrotasks();
+    component.repeatWord(item, 0);
+    expect(platform.play).toHaveBeenCalledTimes(2);
+    expect(component.repetitions()[item.id]).toBe(3);
+  }));
+
+  it('读音补取耗时较长时,返回资源后仍能合并缓冲期间的重复点击', fakeAsync(() => {
+    component.meta.path = 'pages/stu/stu_con';
+    const item = word();
+    let prepare!: (url: string) => void;
+    let start!: () => void;
+    audio.ensure.and.returnValue(new Promise<string>(done => prepare = done));
+    platform.play.and.returnValue(new Promise<void>(done => start = done).then(() => 'played'));
+    void component.play(item);
+    tick(9000);
+    prepare('/generated.mp3');
+    flushMicrotasks();
+    void component.play(item);
+    expect(platform.play).toHaveBeenCalledTimes(1);
+    start();
+    flushMicrotasks();
+  }));
+
+  it('选词时连点正在加载或播放的同一词,只播一次,听完才能再次点读', async () => {
+    component.meta.path = 'pages/stu/stu_abc';
+    const item = word('101', '/apple.mp3');
+    let start!: () => void;
+    platform.play.and.returnValue(new Promise<void>(done => start = done).then(() => 'played'));
+    const first = component.play(item);
+    void component.play(item);
+    expect(platform.play).toHaveBeenCalledTimes(1);
+    start();
+    await first;
+    await component.play(item);
+    expect(platform.play).toHaveBeenCalledTimes(1);
+    expect(component.selectionWordRevealed(item)).toBeFalse();
+    platform.play.calls.first().args[2].onEnded();
+    expect(component.selectionWordRevealed(item)).toBeTrue();
+    await component.play(item);
+    expect(platform.play).toHaveBeenCalledTimes(2);
+    component.ngOnDestroy();
+  });
+
+  it('缺音选词连点只准备一次,失败后可以重新点读', async () => {
+    component.meta.path = 'pages/stu/stu_abc';
+    let fail!: (error: Error) => void;
+    audio.ensure.and.returnValue(new Promise<string>((_, reject) => fail = reject));
+    const item = word();
+    const first = component.play(item);
+    void component.play(item);
+    expect(audio.ensure).toHaveBeenCalledTimes(1);
+    fail(new Error('读音不可用'));
+    await first;
+    audio.ensure.and.resolveTo('/apple.mp3');
+    await component.play(item);
+    expect(platform.play).toHaveBeenCalledTimes(1);
+    component.ngOnDestroy();
+  });
+
+  it('首次加载失败且服务器确认原地址仍有效时,自动重播一次', async () => {
+    component.meta.path = 'pages/stu/stu_abc';
+    platform.play.and.returnValues(Promise.resolve('failed'), Promise.resolve('played'));
+    audio.ensure.and.resolveTo('/apple.mp3');
+    const item = word('101', '/apple.mp3');
+    await component.play(item);
+    expect(platform.play).toHaveBeenCalledTimes(2);
+    expect(component.selectionWordRevealed(item)).toBeFalse();
+    platform.play.calls.mostRecent().args[2].onEnded();
+    expect(component.selectionWordRevealed(item)).toBeTrue();
+  });
+
   it('首次生成有加载状态,成功后同页第二次点读直接复用', async () => {
     const first = component.play(); expect(component.audioPreparing()).toBeTrue(); await first;
     expect(component.audioPreparing()).toBeFalse(); expect(component.current()?.audio).toContain('apple.mp3');

+ 11 - 4
projects/xiaoshu-mobile/src/app/features/learning/learning-page.component.html

@@ -19,7 +19,7 @@
       }
     </div>
   }
-  @if (audioPreparing()) { <p class="readonly-word-note" role="status" aria-live="polite">正在准备读音,首次生成后会自动保存…</p> }
+  @if (audioPreparing() && !pointReadAudio()) { <p class="readonly-word-note" role="status" aria-live="polite">正在准备读音,首次生成后会自动保存…</p> }
   @if (isCoachWordbookSelection && !wordbookStudentId()) {
     @if (!wordbookStudentsLoading() && !wordbookStudentsError()) {
       <div class="empty-state"><p>当前暂无可带练的学员</p></div>
@@ -170,7 +170,11 @@
             @for (word of visibleNewWords(); track word.id) {
               <button type="button" [class.selected]="selected().has(word.id)" (click)="toggleWord(word); play(word)">
                 <span class="check">@if (selected().has(word.id)) { <lucide-icon [img]="icons.Check" [size]="16" /> }</span>
-                <span><strong>{{ word.word }}</strong>@if (selectionWordRevealed(word)) { <small>{{ word.meaning || '暂无释义' }}</small> }</span>
+                <span>
+                  <strong>{{ word.word }}</strong>
+                  @if (pointReadAudio()?.wordId === word.id) { <small role="status">{{ pointReadAudio()?.phase === 'loading' ? '正在加载读音…' : '播放中' }}</small> }
+                  @if (selectionWordRevealed(word)) { <small class="revealed">{{ word.meaning || '暂无释义' }}</small> }
+                </span>
                 <span class="audio" (click)="$event.stopPropagation(); play(word)"><lucide-icon [img]="icons.Volume2" [size]="18" /></span>
               </button>
             } @empty {
@@ -216,6 +220,7 @@
                   }
                   <button type="button" class="word-reveal" [attr.aria-expanded]="selectionWordRevealed(word)" (click)="revealSelectionWord(word)">
                     <strong>{{ word.word }}</strong>
+                    @if (pointReadAudio()?.wordId === word.id) { <small role="status">{{ pointReadAudio()?.phase === 'loading' ? '正在加载读音…' : '播放中' }}</small> }
                     @if (selectionWordRevealed(word)) { <small class="revealed">{{ word.meaning || '暂无释义' }}</small> }
                     @else if (isReadOnlySelectionPage) { <small>{{ courseWordPass(word) > 0 ? selectionCompletionLabel(word) + ' · 点击查看释义' : '点击查看释义' }}</small> }
                   </button>
@@ -266,6 +271,7 @@
       <div>
         <span>第 {{ studyStep() }} / 3 轮</span>
         <strong>{{ studyStep() === 1 ? '顺序学习' : studyStep() === 2 ? '乱序学习' : '中文挑战' }}</strong>
+        @if (studyStep() !== 3) { <span>按住单词向左滑,查看中文释义</span> }
       </div>
       <button type="button" title="重新乱序" aria-label="重新乱序" (click)="shuffleStudyWords()"><lucide-icon [img]="icons.RefreshCw" [size]="19" /></button>
     </div>
@@ -274,10 +280,11 @@
         @let repeatCount = repetitions()[word.id] || 0;
         <button type="button" appPressSwipeLeft (pressSwipeLeft)="revealStudyMeaning(word)" (click)="repeatWord(word, index)">
           <span class="study-copy">
-            <strong class="study-headword">{{ studyStep() === 3 ? word.meaning : word.word }}</strong>
+            <strong class="study-headword">{{ studyStep() === 3 ? (word.meaning || '暂无中文释义') : word.word }}</strong>
             <span class="study-hints">
+              @if (pointReadAudio()?.wordId === word.id && pointReadAudio()?.phase === 'loading') { <span role="status">正在加载读音…</span> }
               @if (studyStep() !== 3 && repeatCount >= 1 && word.phonetic) { <span class="study-phonetic">{{ word.phonetic }}</span> }
-              @if (repeatCount === 2 || (studyStep() !== 3 && studyMeaningRevealed().has(word.id))) { <span class="study-answer">{{ studyStep() === 3 ? word.word : word.meaning }}</span> }
+              @if (repeatCount === 2 || (studyStep() !== 3 && studyMeaningRevealed().has(word.id))) { <span class="study-answer">{{ studyStep() === 3 ? word.word : (word.meaning || '暂无中文释义') }}</span> }
             </span>
           </span>
           <span class="repeat-dots" aria-label="跟读次数">

+ 70 - 32
projects/xiaoshu-mobile/src/app/features/learning/learning-page.component.ts

@@ -358,6 +358,7 @@ export class LearningPageComponent implements OnInit, OnDestroy {
   private readonly listeningPool = inject(ListeningPoolService);
   private readonly wordAudio = inject(WordAudioService);
   readonly audioPreparing = signal(false);
+  readonly pointReadAudio = signal<{ wordId: string; phase: 'loading' | 'playing'; since: number } | null>(null);
   private audioRequest = 0;
   private readonly wordPreviewPageSize = 30;
   private examTimer: ReturnType<typeof setInterval> | null = null;
@@ -390,14 +391,13 @@ export class LearningPageComponent implements OnInit, OnDestroy {
   }
 
   ngOnDestroy(): void {
-    this.audioRequest++;
+    this.stopWordPlayback();
     this.calendarRequestId++;this.calendarRequest?.unsubscribe();this.selectionRequest?.unsubscribe();
     this.wordbookStudentsRequest?.unsubscribe();
     this.choiceOptionsVersion++;
     this.choiceOptionsRequest?.unsubscribe();
     this.stopExamTimer();
     this.examHistoryRequest?.unsubscribe();this.examLoadRequest?.unsubscribe();
-    this.platform.stopAudio();
   }
 
   get isNodePage(): boolean {
@@ -637,10 +637,7 @@ export class LearningPageComponent implements OnInit, OnDestroy {
     const previous = this.wordPreviewPage();
     this.wordPreviewPage.set(target);
     if (this.isHistoryWordView) {
-      this.audioRequest++;
-      this.platform.stopAudio();
-      this.audioPreparing.set(false);
-      this.historyAudioWordId.set('');
+      this.stopWordPlayback();
       const start = (target - 1) * this.wordPreviewPageSize;
       this.words.set(this.historyPreviewWords.slice(start, start + this.wordPreviewPageSize));
       setTimeout(() => document.getElementById('readonly-word-title')?.scrollIntoView({ behavior: 'smooth', block: 'start' }));
@@ -768,7 +765,7 @@ export class LearningPageComponent implements OnInit, OnDestroy {
 
   selectCoursePass(pass: number): void {
     if (this.selectionLocked() || pass === this.coursePass() || pass < 0 || pass > 3) return;
-    this.audioRequest++;this.platform.stopAudio();this.audioPreparing.set(false);
+    this.stopWordPlayback();
     this.selectionRevealed.set(new Set());
     this.bulkSelection.set(null);
     this.courseSelectionNeedsRebase = false;
@@ -962,36 +959,62 @@ export class LearningPageComponent implements OnInit, OnDestroy {
     });
   }
 
+  private stopWordPlayback(): void {
+    this.audioRequest++;
+    this.platform.stopAudio();
+    this.audioPreparing.set(false);
+    this.historyAudioWordId.set('');
+    this.pointReadAudio.set(null);
+  }
+
   async play(word = this.current()): Promise<void> {
     if (this.isReadOnlySelectionPage || (this.isReadOnlyWordView && !this.isHistoryWordView) || !word) return;
-    this.prepareWordAudio(word);
+    const selection = this.isRefineSelectionPage || this.isNewWordSelectionPage;
+    const pointReading = selection || this.isStudyListPage;
+    const pending = this.pointReadAudio();
+    // Study taps may replay once sound starts. On the selection list let the word finish first.
+    if (pointReading && pending?.wordId === word.id && (selection || pending.phase === 'loading')
+      && (this.audioPreparing() || Date.now() - pending.since < 8000)) return;
+    if (pointReading) this.pointReadAudio.set({ wordId: word.id, phase: 'loading', since: Date.now() });
     const request = ++this.audioRequest, focusedWord = this.current(), step = this.studyStep();
     const active = () => request === this.audioRequest && this.current() === focusedWord && this.studyStep() === step;
     this.audioPreparing.set(false);
     if (this.isHistoryWordView) this.historyAudioWordId.set(word.id);
+    const finishPlayback = () => {
+      this.historyAudioWordId.set('');
+      if (pointReading) this.pointReadAudio.set(null);
+    };
     const playAudio = async (url: string, silentFailure = false) => {
-      const status = await (this.isHistoryWordView || this.isSelectionPage || this.isStudyListPage
+      const playback = this.isHistoryWordView || this.isSelectionPage || this.isStudyListPage
         ? this.platform.play(url, silentFailure, {
           onEnded: () => {
             if (!active()) return;
             if (this.isHistoryWordView) this.historyWordRevealed.update(current => new Set(current).add(word.id));
             else if (!this.isStudyListPage) this.selectionRevealed.update(current => new Set(current).add(word.id));
-            this.historyAudioWordId.set('');
+            finishPlayback();
           },
           onError: () => {
             if (!active()) return;
-            this.historyAudioWordId.set('');
+            finishPlayback();
             this.platform.toast('音频播放中断,请再点一次单词重试', 'error');
           },
         })
-        : this.platform.play(url, silentFailure));
-      if (status !== 'played' && active()) this.historyAudioWordId.set('');
+        : this.platform.play(url, silentFailure);
+      this.prepareWordAudio(word);
+      const status = await playback;
+      if (active() && pointReading && status === 'played' && this.pointReadAudio()) {
+        this.pointReadAudio.set({ wordId: word.id, phase: 'playing', since: Date.now() });
+      }
       return status;
     };
     const original = word.audio?.trim();
     if (original) {
       const status = await playAudio(this.wordAudioUrl(original), true);
-      if (status !== 'failed' || !active()) return;
+      if (!active()) return;
+      if (status !== 'failed') {
+        if (status !== 'played') finishPlayback();
+        return;
+      }
     } else this.platform.stopAudio();
     this.audioPreparing.set(true);
     if (this.isHistoryWordView) this.historyAudioWordId.set(word.id);
@@ -999,15 +1022,20 @@ export class LearningPageComponent implements OnInit, OnDestroy {
       const url = await this.wordAudio.ensure(word.wordId, !!original);
       if (!active()) return;
       word.audio = url;
-      if (original && this.wordAudioUrl(original) === this.wordAudioUrl(url)) {
-        this.historyAudioWordId.set('');
+      if (pointReading) {
+        this.audioPreparing.set(false);
+        this.pointReadAudio.set({ wordId: word.id, phase: 'loading', since: Date.now() });
+      }
+      if (!pointReading && original && this.wordAudioUrl(original) === this.wordAudioUrl(url)) {
+        finishPlayback();
         this.platform.toast('音频暂时无法播放,请检查网络后重试', 'error');
         return;
       }
-      await playAudio(this.wordAudioUrl(url));
+      const status = await playAudio(this.wordAudioUrl(url));
+      if (active() && status !== 'played') finishPlayback();
     } catch (error) {
       if (active()) {
-        this.historyAudioWordId.set('');
+        finishPlayback();
         this.platform.toast(error instanceof Error ? error.message : '读音暂时不可用,请再点喇叭重试', 'error');
       }
     } finally {
@@ -1032,7 +1060,13 @@ export class LearningPageComponent implements OnInit, OnDestroy {
   }
 
   repeatWord(word: Word, index: number): void {
-    this.studyMeaningRevealed.update(current => new Set([...current].filter(id => id !== word.id)));
+    if (this.studyMeaningRevealed().has(word.id)) {
+      this.studyMeaningRevealed.update(current => {
+        const revealed = new Set(current);
+        revealed.delete(word.id);
+        return revealed;
+      });
+    }
     const count = this.repetitions()[word.id] ?? 0;
     if (this.studyStep() === 1 && index > 0) {
       const previous = this.words()[index - 1];
@@ -1051,9 +1085,10 @@ export class LearningPageComponent implements OnInit, OnDestroy {
   }
 
   shuffleStudyWords(): void {
-    this.audioRequest++;this.platform.stopAudio();this.audioPreparing.set(false);
+    this.stopWordPlayback();
     this.selectionRevealed.set(new Set());
     this.words.set(shuffledStudy(this.words()));
+    this.prepareWordAudio(this.words()[0]);
     this.repetitions.set({});
     this.studyMeaningRevealed.set(new Set());
   }
@@ -1103,8 +1138,8 @@ export class LearningPageComponent implements OnInit, OnDestroy {
       return;
     }
     this.currentIndex.update((value) => value + 1);
+    void this.play();
     this.prepareChoiceOptions();
-    setTimeout(() => this.play(), 150);
   }
 
   spellLetter(index: number): void {
@@ -1549,7 +1584,7 @@ export class LearningPageComponent implements OnInit, OnDestroy {
   }
   selectNewWordBucket(bucket: 'pending' | 'completed'): void {
     if (this.activeSelectionBucket() === bucket) return;
-    this.audioRequest++;this.platform.stopAudio();this.audioPreparing.set(false);
+    this.stopWordPlayback();
     this.selectionRequest?.unsubscribe();
     this.activeSelectionBucket.set(bucket);
     this.selectionPage.set(1);
@@ -1561,7 +1596,7 @@ export class LearningPageComponent implements OnInit, OnDestroy {
 
   goToNewWordPage(page: number): void {
     if (this.selectionLoading() || page < 1 || page > this.newWordPageCount() || page === this.selectionPage()) return;
-    this.audioRequest++;this.platform.stopAudio();this.audioPreparing.set(false);
+    this.stopWordPlayback();
     this.selectionPage.set(page);
     if (this.legacyNewWords) { this.showLegacyNewWordPage(); return; }
     this.loadSelection();
@@ -1576,6 +1611,7 @@ export class LearningPageComponent implements OnInit, OnDestroy {
     this.newWordCounts.set({ pending: pending.length, completed: completed.length });
     this.selectionTotal.set(bucket.length);
     this.words.set(bucket.slice(start, start + this.newWordPageSize));
+    this.prepareWordAudio(this.words()[0]);
     for (const word of all) this.newWordSelectionCache.set(word.id, word);
     this.error.set('');
     this.selectionLoading.set(false);
@@ -1617,6 +1653,7 @@ export class LearningPageComponent implements OnInit, OnDestroy {
       const student = this.session.student() ?? this.session.user();this.selectionLoading.set(true);
       this.selectionRequest=this.api.get<unknown>('e_ck_list',{checkwords:2,nids:this.query('nids')||this.query('nid'),pnid:this.query('pnid'),learningPass:this.coursePass(),modelId:52,cpage:this.selectionPage(),psize:100,compact:true,uid:student?.userId}).pipe(finalize(()=>{this.selectionLoading.set(false);this.loading.set(false);})).subscribe({next:({result,page})=>{
         accept(result,page?.itemCount);
+        if (!more) this.prepareWordAudio(this.visibleCourseWords()[0]);
         if (rebaseFromPage !== undefined) this.courseSelectionNeedsRebase = false;
         const merged=new Map(this.courseSelectionCache().map(word=>[word.id,word]));
         for(const word of this.words()) merged.set(word.id,word);
@@ -1663,6 +1700,7 @@ export class LearningPageComponent implements OnInit, OnDestroy {
           return;
         }
         this.words.set(incoming);
+        this.prepareWordAudio(incoming[0]);
         for (const word of incoming) this.newWordSelectionCache.set(word.id, word);
         const counts = {pending: pendingCount, completed: completedCount};
         this.newWordCounts.set(counts);
@@ -1740,7 +1778,7 @@ export class LearningPageComponent implements OnInit, OnDestroy {
     }
     const words = this.isStudyListPage ? source : this.shuffle(source);
     this.words.set(words);
-    this.prepareWordAudio(words[0]);
+    if (!this.isListeningPage && !this.isSpellingPage) this.prepareWordAudio(words[0]);
     if (this.isStudyListPage) {
       this.studyStep.set(1);
       this.repetitions.set({});
@@ -1752,11 +1790,11 @@ export class LearningPageComponent implements OnInit, OnDestroy {
       const round = [...this.readAllLearningWords(), ...words];
       this.listeningPool.load(round.map(word => word.id)).subscribe({ error: () => undefined });
     } else if (this.isListeningPage) {
+      void this.play();
       this.prepareChoiceOptions();
-      setTimeout(() => this.play(), 120);
     } else if (this.isSpellingPage) {
       this.prepareSpelling();
-      setTimeout(() => this.play(), 120);
+      void this.play();
     }
   }
 
@@ -1764,8 +1802,10 @@ export class LearningPageComponent implements OnInit, OnDestroy {
     if (this.studyStep() < 3) {
       const next = (this.studyStep() + 1) as 2 | 3;
       this.selectionRevealed.set(new Set());
+      this.pointReadAudio.set(null);
       this.studyStep.set(next);
       this.words.set(shuffledStudy(this.words()));
+      this.prepareWordAudio(this.words()[0]);
       this.repetitions.set({});
       this.studyMeaningRevealed.set(new Set());
       this.platform.toast(next === 2 ? '进入乱序学习' : '进入中文挑战', 'success');
@@ -2441,9 +2481,7 @@ export class LearningPageComponent implements OnInit, OnDestroy {
   private clearLearningStorage(): void { this.draft().clear(); }
 
   private resetPageState(): void {
-    this.audioRequest++;
-    this.platform.stopAudio();
-    this.audioPreparing.set(false);
+    this.stopWordPlayback();
     this.outsideChoicePool = null;
     this.choicesLoading.set(false);
     this.choiceOptionsVersion++;
@@ -2454,7 +2492,6 @@ export class LearningPageComponent implements OnInit, OnDestroy {
     this.words.set([]);
     this.historyPreviewWords = [];
     this.historyWordRevealed.set(new Set());
-    this.historyAudioWordId.set('');
     this.historySources.set([]);
     this.wordPreviewPage.set(1);
     this.wordPreviewTotal.set(0);
@@ -2513,9 +2550,10 @@ export class LearningPageComponent implements OnInit, OnDestroy {
       wordId,
       nodeId: String(item['NodeID'] ?? detail['NodeID'] ?? item['nodeId'] ?? ''),
       word: String(item['Title'] ?? detail['Title'] ?? item['word'] ?? detail['word'] ?? item['Word'] ?? ''),
-      meaning: String(item['sy'] ?? detail['sy'] ?? item['jssy'] ?? detail['jssy'] ?? item['Translate'] ?? detail['Translate'] ?? item['Meaning'] ?? ''),
+      meaning: [item['sy'], detail['sy'], item['jssy'], detail['jssy'], item['Translate'], detail['Translate'], item['Meaning'], item['meaning']]
+        .map(value => String(value ?? '').trim()).find(Boolean) || '',
       phonetic: [item['yb'], detail['yb'], item['Phonetic'], detail['Phonetic'], item['phonetic'], detail['phonetic']].map(value => String(value ?? '').trim()).find(Boolean) || '',
-      audio: [item['yp'], detail['yp'], item['dy'], detail['dy']].map(value => String(value ?? '').trim()).find(Boolean) || '',
+      audio: [typeof item['audio'] === 'string' ? item['audio'] : '', item['yp'], detail['yp'], item['dy'], detail['dy']].map(value => String(value ?? '').trim()).find(Boolean) || '',
     };
   }
 

+ 10 - 0
projects/xiaoshu-mobile/src/app/shared/press-swipe-left.directive.spec.ts

@@ -22,6 +22,16 @@ describe('长按左滑',()=>{
     expect(host.reveals).toBe(1);expect(host.clicks).toBe(0);
     pointer('pointerdown',150,30,600);pointer('pointerup',150,30,650);click();expect(host.clicks).toBe(1);
   });
+  it('按住后略微斜向左滑也显示中文,松手不计次', () => {
+    const {host,pointer,click}=setup();
+    pointer('pointerdown',150,30,0);
+    pointer('pointermove',127,40,470);
+    pointer('pointermove',90,54,520);
+    pointer('pointerup',90,54,530);
+    click();
+    expect(host.reveals).toBe(1);
+    expect(host.clicks).toBe(0);
+  });
   for(const [name,x,y,time] of [['短划',100,30,100],['右划',210,30,500],['竖向滚动',145,80,500],['距离不足',135,30,500]] as const){
     it(name+'不显示中文且不误算点击',()=>{
       const {host,pointer,click}=setup();pointer('pointerdown',150,30,0);pointer('pointermove',x,y,time);pointer('pointerup',x,y,time+10);click();

+ 2 - 1
projects/xiaoshu-mobile/src/app/shared/press-swipe-left.directive.ts

@@ -43,7 +43,8 @@ export class PressSwipeLeftDirective {
     if (!gesture || gesture.id !== event.pointerId || gesture.revealed) return;
     const dx = event.clientX - gesture.x, dy = event.clientY - gesture.y;
     const held = event.timeStamp - gesture.started >= 450;
-    if (Math.abs(dy) > 18 || dx > 18 || (!held && Math.hypot(dx, dy) > 10)) {
+    const scrolling = Math.abs(dy) > 18 && -dx < 1.5 * Math.abs(dy);
+    if (scrolling || dx > 18 || (!held && Math.hypot(dx, dy) > 10)) {
       this.suppressClick = true;
       this.gesture = undefined;
       return;

+ 8 - 3
scripts/check-three-tap-reading-browser.mjs

@@ -58,10 +58,15 @@ try{
   assert.equal(await row().locator('.study-answer').innerText(),firstMeaning);assert.equal(await row().locator('.repeat-dots .done').count(),0);
   await row().click();await settle();assert.equal(await row().locator('.study-answer').count(),0);assert.equal(await row().locator('.repeat-dots .done').count(),1);
   // Real touch gesture via CDP, including native scroll cancellation on vertical movement.
-  const cdp=await context.newCDPSession(page);box=await row().boundingBox();
+  const cdp=await context.newCDPSession(page);
+  const unread=page.locator('.repeat-list > button').nth(1);
+  const unreadTitle=await unread.locator('strong').innerText();
+  box=await unread.boundingBox();
   const touch=async(type,x,y)=>cdp.send('Input.dispatchTouchEvent',{type,touchPoints:type==='touchEnd'?[]:[{x,y}]});
-  await touch('touchStart',box.x+box.width-30,box.y+25);await new Promise(r=>setTimeout(r,480));await touch('touchMove',box.x+box.width-90,box.y+25);await touch('touchEnd');await settle();
-  assert.equal(await row().locator('.study-answer').innerText(),firstMeaning);assert.equal(await row().locator('.repeat-dots .done').count(),1);
+  await touch('touchStart',box.x+box.width-30,box.y+15);await new Promise(r=>setTimeout(r,480));
+  await touch('touchMove',box.x+box.width-90,box.y+39);await touch('touchEnd');await settle();
+  assert.equal(await unread.locator('.study-answer').innerText(),words.find(w=>w.Title===unreadTitle).sy);
+  assert.equal(await unread.locator('.repeat-dots .done').count(),0);assert.equal(await row().locator('.repeat-dots .done').count(),1);
   await page.getByRole('button',{name:'重新乱序',exact:true}).click();await settle();assert.equal(await page.locator('.study-answer').count(),0);assert.equal(await page.locator('.repeat-dots .done').count(),0);
   await page.setViewportSize({width:375,height:420});await page.evaluate(()=>window.scrollTo(0,0));await settle();
   box=await row().boundingBox();