fix: SVG动画改为用户手动播放

This commit is contained in:
margrop
2026-10-31 20:43:10 +08:00
parent d832de1742
commit 5dbc42c64f
6 changed files with 120 additions and 8 deletions

View File

@@ -146,7 +146,7 @@ Practice statistics show total practice, accuracy and active months, with distri
### Explanations and demos
- **🎬 SVG animated explanations**: AI generates step-by-step SVG animations of the solution, with play/pause, seeking, replay and full screen. Animation text follows the interface language; Chinese and English versions are kept separately, and switching the language shows the matching version automatically. On by default; turn it off in **Settings → General**.
- **🎬 SVG animated explanations**: AI generates step-by-step SVG animations of the solution that stay paused on the first frame when the page opens or the animation changes; click Play to start. The player supports play/pause, seeking, replay and full screen. Animation text follows the interface language; Chinese and English versions are kept separately, and switching the language shows the matching version automatically. On by default; turn it off in **Settings → General**.
- **🔊 Voice narration**: click the speaker icon in the player; the animation waits for each step to be read before moving on, and the speed is adjustable. Choose the browser voice or cloud TTS (see [Cloud voice narration](#-cloud-voice-narration)). Older animations without a narration script read the on-screen subtitles, or click **Add narration** to have AI write only the script while keeping the picture unchanged.
- **📐 GeoGebra demos**: for math and physics questions, AI can generate interactive GeoGebra figures. Off by default; turn it on in **Settings → General**.
- Generated animations and GeoGebra demos can be deleted (with confirmation).

View File

@@ -146,7 +146,7 @@
### 讲解与演示
- **🎬 SVG 动画讲解**:AI 按解题思路生成分步骤的 SVG 动画,支持播放/暂停、拖动进度、重播和全屏;动画文字与界面语言一致,中英文版本分别保存,切换语言时自动显示对应版本。默认开启,可在「设置 → 通用」中关闭。
- **🎬 SVG 动画讲解**:AI 按解题思路生成分步骤的 SVG 动画,打开页面或切换动画时停在首帧,点击播放后才开始;支持播放/暂停、拖动进度、重播和全屏;动画文字与界面语言一致,中英文版本分别保存,切换语言时自动显示对应版本。默认开启,可在「设置 → 通用」中关闭。
- **🔊 语音讲解**:点击播放器上的喇叭开启,画面等语音读完再进入下一步,语速可调。语音可选浏览器本地语音或云端 TTS(见[云端语音讲解](#-云端语音讲解));旧动画没有讲解稿时朗读画面字幕,也可点击「补充讲解稿」由 AI 只补写讲解稿,画面保持不变。
- **📐 GeoGebra 动态演示**:数学、物理题可由 AI 生成交互式 GeoGebra 图形。默认关闭,可在「设置 → 通用」中开启。
- 已生成的动画讲解和 GeoGebra 演示都可删除(需二次确认)。

View File

@@ -52,7 +52,7 @@
## 配图和动态讲解
- **SVG 配图**:由 AI 根据题目生成静态 SVG,供详情、练习和打印使用;原图可单独查看。
- **SVG 动画讲解**:按解题思路分步骤演示,支持暂停、拖动进度、重播和全屏,个人设置默认开启。点击播放器上的喇叭开启语音讲解(默认关闭,开启后会记住),朗读每一步(默认用浏览器的语音合成;管理员开启云端语音后由服务端合成,所有设备音色一致),画面等语音读完再进入下一步(等待时停在当前步骤完整的画面上,动画外框高亮提示),语速可在 0.75×~1.5× 间切换。旧动画没有讲解稿时朗读画面底部的字幕;点击动画上方的「补充讲解稿」可由 AI 按现有画面补写讲解稿,画面不变,不需要重新生成动画(计 1 次 AI 动画讲解用量)。已有讲解稿时按钮显示为「重写讲解稿」。使用云端语音时,首次开启语音会一次合成整个动画的讲解语音,动画上方另有「重新生成语音」可重新合成;两者都会登记到「后台任务」中显示进度(消耗语音服务商额度,不计 AI 次数)。已生成云端语音的动画再次打开时默认开启语音讲解。动画文字跟随界面语言,中英文版本分别生成和保存,切换语言时自动显示对应版本。
- **SVG 动画讲解**:按解题思路分步骤演示,打开页面或切换动画时停在首帧,须点击播放才开始,支持暂停、拖动进度、重播和全屏,个人设置默认开启。点击播放器上的喇叭开启语音讲解(默认关闭,开启后会记住),朗读每一步(默认用浏览器的语音合成;管理员开启云端语音后由服务端合成,所有设备音色一致),画面等语音读完再进入下一步(等待时停在当前步骤完整的画面上,动画外框高亮提示),语速可在 0.75×~1.5× 间切换。旧动画没有讲解稿时朗读画面底部的字幕;点击动画上方的「补充讲解稿」可由 AI 按现有画面补写讲解稿,画面不变,不需要重新生成动画(计 1 次 AI 动画讲解用量)。已有讲解稿时按钮显示为「重写讲解稿」。使用云端语音时,首次开启语音会一次合成整个动画的讲解语音,动画上方另有「重新生成语音」可重新合成;两者都会登记到「后台任务」中显示进度(消耗语音服务商额度,不计 AI 次数)。已生成云端语音的动画再次打开时默认开启语音讲解。动画文字跟随界面语言,中英文版本分别生成和保存,切换语言时自动显示对应版本。
- **GeoGebra 动态演示**:供数学、物理题生成交互图形,个人设置默认关闭。
已生成的动画和 GeoGebra 演示可在确认后删除。生成的图形和解答需要人工核对,尤其是几何位置、计数过程和结论。

View File

@@ -52,7 +52,7 @@ Unrated questions are not assigned a paper level by the default rule alone. Rege
## Figures and animated explanations
- **SVG figures**: static SVG generated by the AI from the question, used on the detail page, in practice and in printouts; the original image can still be viewed separately.
- **SVG animated explanations**: step-by-step demonstrations of the solution with pause, seeking, replay and full screen; enabled by default in personal settings. Click the speaker icon in the player to turn on voice narration (off by default and remembered once on). Each step is read aloud (by the browser's speech synthesis by default; when an admin turns on cloud voice, the server synthesizes it so every device hears the same voice), the animation waits for the narration before moving on (it pauses on the complete current step and highlights the frame border while waiting), and the speed cycles between 0.75× and 1.5×. Older animations without a narration script read the subtitles at the bottom of the picture. Click **Add narration** above the animation to have AI write a script for the existing picture without regenerating the animation (counts as one animated-explanation AI use). When a script exists, the button reads **Rewrite narration**. With cloud voice on, turning on narration for the first time synthesizes the whole animation's voice at once, and **Regenerate voice** above the animation synthesizes it again; both appear in background tasks with progress (they use the speech provider's quota, not the AI daily limit). Animations whose cloud voice has been generated open with narration on. Animation text follows the interface language; Chinese and English versions are generated and saved separately, and switching the language shows the matching version automatically.
- **SVG animated explanations**: the animation stays paused on the first frame when opened or changed; click Play to start. Step-by-step demonstrations of the solution with pause, seeking, replay and full screen; enabled by default in personal settings. Click the speaker icon in the player to turn on voice narration (off by default and remembered once on). Each step is read aloud (by the browser's speech synthesis by default; when an admin turns on cloud voice, the server synthesizes it so every device hears the same voice), the animation waits for the narration before moving on (it pauses on the complete current step and highlights the frame border while waiting), and the speed cycles between 0.75× and 1.5×. Older animations without a narration script read the subtitles at the bottom of the picture. Click **Add narration** above the animation to have AI write a script for the existing picture without regenerating the animation (counts as one animated-explanation AI use). When a script exists, the button reads **Rewrite narration**. With cloud voice on, turning on narration for the first time synthesizes the whole animation's voice at once, and **Regenerate voice** above the animation synthesizes it again; both appear in background tasks with progress (they use the speech provider's quota, not the AI daily limit). Animations whose cloud voice has been generated open with narration on. Animation text follows the interface language; Chinese and English versions are generated and saved separately, and switching the language shows the matching version automatically.
- **GeoGebra interactive demos**: interactive figures for math and physics questions; disabled by default in personal settings.
Generated animations and GeoGebra demos can be deleted after confirmation. Check generated figures and solutions manually, especially geometric positions, counting steps and conclusions.

View File

@@ -0,0 +1,105 @@
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import type { Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { SvgAnimationPlayer } from '@/components/svg-animation-player';
import { LanguageProvider } from '@/contexts/LanguageContext';
const narration = vi.hoisted(() => ({ stop: vi.fn(), update: vi.fn(), prime: vi.fn() }));
vi.mock('@/lib/use-svg-narration', () => ({
useSvgNarration: () => ({ ...narration, enabled: true, holding: false, speaking: false }),
}));
let container: HTMLDivElement;
let root: Root;
const svg = '<svg viewBox="0 0 800 500"><animate attributeName="x" dur="10s"/></svg>';
beforeEach(() => {
vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
vi.stubGlobal('requestAnimationFrame', vi.fn(() => 1));
vi.stubGlobal('cancelAnimationFrame', vi.fn());
container = document.createElement('div');
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(async () => {
await act(async () => root.unmount());
container.remove();
vi.unstubAllGlobals();
});
async function render(source = svg) {
await act(async () => root.render(<LanguageProvider><SvgAnimationPlayer svg={source} /></LanguageProvider>));
}
async function load() {
const iframe = container.querySelector('iframe')!;
const element = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
const timeline = { pauseAnimations: vi.fn(), unpauseAnimations: vi.fn(), setCurrentTime: vi.fn(), getCurrentTime: () => 0 };
Object.assign(element, timeline);
const cssAnimation = { pause: vi.fn(), play: vi.fn(), currentTime: 200 };
vi.spyOn(iframe.contentDocument!, 'querySelector').mockReturnValue(element);
Object.assign(iframe.contentDocument!, { getAnimations: () => [cssAnimation] });
await act(async () => iframe.dispatchEvent(new Event('load')));
return { iframe, timeline, cssAnimation };
}
function button(label: string) {
return container.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`)!;
}
describe('SVG 动画必须手工播放', () => {
it('加载后 SMIL 和 CSS 停在首帧,画面与朗读均不自动开始', async () => {
await render();
expect(button('播放').disabled).toBe(true);
const { iframe, timeline, cssAnimation } = await load();
expect(timeline.pauseAnimations).toHaveBeenCalled();
expect(timeline.setCurrentTime).toHaveBeenCalledWith(0);
expect(cssAnimation.pause).toHaveBeenCalled();
expect(cssAnimation.currentTime).toBe(0);
expect(timeline.unpauseAnimations).not.toHaveBeenCalled();
expect(cssAnimation.play).not.toHaveBeenCalled();
expect(narration.prime).not.toHaveBeenCalled();
expect(requestAnimationFrame).not.toHaveBeenCalled();
expect(button('播放').disabled).toBe(false);
expect(iframe.style.visibility).toBe('visible');
});
it('点击播放才恢复两条时间轴和朗读,点击暂停后停止', async () => {
await render();
const { timeline, cssAnimation } = await load();
await act(async () => button('播放').click());
expect(timeline.unpauseAnimations).toHaveBeenCalledOnce();
expect(cssAnimation.play).toHaveBeenCalledOnce();
expect(narration.prime).toHaveBeenCalledOnce();
expect(requestAnimationFrame).toHaveBeenCalledOnce();
await act(async () => button('暂停').click());
expect(timeline.pauseAnimations).toHaveBeenCalledTimes(2);
expect(cssAnimation.pause).toHaveBeenCalledTimes(2);
expect(button('播放')).toBeTruthy();
});
it('切换或重新生成动画后重新停在首帧', async () => {
await render();
await load();
await act(async () => button('播放').click());
await render(svg.replace('10s', '12s'));
expect(container.querySelector('iframe')!.style.visibility).toBe('hidden');
const { timeline, cssAnimation } = await load();
expect(timeline.setCurrentTime).toHaveBeenCalledWith(0);
expect(timeline.unpauseAnimations).not.toHaveBeenCalled();
expect(cssAnimation.play).not.toHaveBeenCalled();
expect(button('播放')).toBeTruthy();
});
it('手工点击重播会从头开始播放', async () => {
await render();
const { timeline, cssAnimation } = await load();
await act(async () => button('重播').click());
expect(timeline.setCurrentTime).toHaveBeenLastCalledWith(0);
expect(timeline.unpauseAnimations).toHaveBeenCalledOnce();
expect(cssAnimation.play).toHaveBeenCalledOnce();
});
});

View File

@@ -33,6 +33,7 @@ export function SvgAnimationPlayer({ svg, errorItemId }: SvgAnimationPlayerProps
const containerRef = useRef<HTMLDivElement>(null);
const iframeRef = useRef<HTMLIFrameElement>(null);
const svgRef = useRef<SVGSVGElement | null>(null);
const [loadedSvg, setLoadedSvg] = useState<string | null>(null);
const [playing, setPlaying] = useState(false);
const [current, setCurrent] = useState(0);
const [nativeFullscreen, setNativeFullscreen] = useState(false);
@@ -98,10 +99,14 @@ export function SvgAnimationPlayer({ svg, errorItemId }: SvgAnimationPlayerProps
const handleLoad = () => {
svgRef.current = iframeRef.current?.contentDocument?.querySelector("svg") ?? null;
setSubtitleNarration(svgRef.current ? extractSubtitleNarration(svgRef.current) : null);
stopNarration(0);
// SMIL 和 CSS 时间轴都停在首帧,只有用户点击播放或重播才恢复。
pauseAnimation();
svgRef.current?.setCurrentTime(0);
cssAnimations().forEach((animation) => { animation.currentTime = 0; });
setSubtitleNarration(svgRef.current ? extractSubtitleNarration(svgRef.current) : null);
setCurrent(0);
setPlaying(!!svgRef.current);
setLoadedSvg(svgRef.current ? svg : null);
};
const toggleFullscreen = async () => {
@@ -186,9 +191,9 @@ export function SvgAnimationPlayer({ svg, errorItemId }: SvgAnimationPlayerProps
waitingForVoice && "border-primary ring-2 ring-primary/40"
)}
// 全屏时按宽高比放到最大,留出控制栏的高度
style={fullscreen
style={{ visibility: loadedSvg === svg ? "visible" : "hidden", ...(fullscreen
? { aspectRatio, width: `min(100%, calc((100dvh - 96px) * ${aspectRatio}))` }
: { aspectRatio }}
: { aspectRatio }) }}
/>
<div className={cn("mx-auto flex w-full items-center gap-2", fullscreen ? "max-w-5xl text-white" : "max-w-3xl")}>
<Button
@@ -197,6 +202,7 @@ export function SvgAnimationPlayer({ svg, errorItemId }: SvgAnimationPlayerProps
// 全屏时控制栏文字为白色,播放按钮是白底,图标需保持深色
className="h-8 w-8 shrink-0 p-0 text-foreground"
onClick={playing ? pause : play}
disabled={loadedSvg !== svg}
aria-label={playing ? t.svgAnimation.pause : t.svgAnimation.play}
title={playing ? t.svgAnimation.pause : t.svgAnimation.play}
>
@@ -207,6 +213,7 @@ export function SvgAnimationPlayer({ svg, errorItemId }: SvgAnimationPlayerProps
size="sm"
className={cn("h-8 w-8 shrink-0 p-0", fullscreen && "text-white hover:bg-white/20 hover:text-white")}
onClick={() => { seek(0); play(); }}
disabled={loadedSvg !== svg}
aria-label={t.svgAnimation.replay}
title={t.svgAnimation.replay}
>