ChatBotPage.tsx 130 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331
  1. import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react';
  2. import { useNavigate, useSearchParams, useLocation } from 'react-router-dom';
  3. import { message as antMessage } from 'antd';
  4. import { v4 as uuidv4 } from 'uuid';
  5. import { useAppStore } from '@/store';
  6. import { AudioRecorder, type FrequencyFrame } from '@/utils/audioRecorder';
  7. import { AudioPlayer } from '@/utils/audioPlayer';
  8. import { WebSocketManager } from '@/utils/websocket';
  9. import { prepareMobileAudio, requestVolumeControl, isMobileDevice } from '@/utils/audioHelper';
  10. import {
  11. setStorage,
  12. getStorage,
  13. getUserLevel,
  14. getHasSharedAvatar,
  15. STORAGE_KEYS,
  16. markRouteVisited,
  17. getUserId,
  18. getVisitedRoutes,
  19. setUserLevel,
  20. getCurrentBackgroundImageUrl,
  21. getCurrentBackgroundImageId,
  22. getCurrentBackgroundImageOpacity,
  23. syncBackgroundImageToStorage,
  24. setUserName,
  25. getUserToken,
  26. setUserToken,
  27. clearUserSessionAndRedirectToBegin,
  28. ROUTE_ORDER,
  29. } from '@/utils/storage';
  30. import { onScreenResize, calculateLayout, type CalculatedLayout, updateTooSmallFlag } from '@/utils/screenSize';
  31. import { performanceLogger } from '@/utils/logger';
  32. import { getUserInfo, updateUserUIState, getUserUIState, getAvatarGifs, type AvatarGifSet, ensureSession } from '@/utils/api';
  33. import { px2vw, px2vh, px2vmin } from '@/utils/viewport';
  34. import type { Message, EnergyStoneSpawnMessage } from '@/types';
  35. import '@/styles/chatbot-fix.css';
  36. import { getOssUrl } from '@/utils/oss';
  37. import { AudioWave, type AudioWaveHandle } from '@/components/AudioWave';
  38. const avatarC = getOssUrl('Avatar-C.svg');
  39. const avatarGift = getOssUrl('Gift.gif');
  40. const audioButton = getOssUrl('audio-button.png');
  41. const avatarHint = getOssUrl('Avatar-hint.png');
  42. const microphoneIcon = getOssUrl('microphone-icon.svg');
  43. const progressRing = getOssUrl('progress-ring.svg');
  44. const progressFull = getOssUrl('progress-full.svg');
  45. const tapToChat = getOssUrl('TapToChat.svg');
  46. const cancelIcon = getOssUrl('cancel-icon.svg');
  47. const sendIcon = getOssUrl('send-icon.svg');
  48. const tooltipsCancel = getOssUrl('tooltips-cancel.svg');
  49. const tooltipsSend = getOssUrl('tooltips-send.svg');
  50. const tooltipsProgressBar = getOssUrl('tooltips-progress-bar.svg');
  51. const missionEnergyStone = getOssUrl('Mission-Energy-Stone.png');
  52. const conversationEnergyStone = getOssUrl('Conversation-Energy-Stone.png');
  53. const missionEnergyStoneHint = getOssUrl('Mission-Energy-Stone-hint.png');
  54. const conversationEnergyStoneHint = getOssUrl('Conversation-Energy-Stone-hint.png');
  55. const YpImage = getOssUrl('yp.png');
  56. import { useEnergyStones, type EnergyStoneEventPayload } from '@/hooks/useEnergyStones';
  57. import { MissionEnergyStoneModal } from '@/components/MissionEnergyStoneModal';
  58. const MAX_RECORDING_DURATION_MS = 60_000;
  59. const AVATAR_C_UNLOCK_THRESHOLD_MS = 60_000;
  60. const COUNTDOWN_THRESHOLD_MS = 10_000;
  61. const WS_URL = import.meta.env.VITE_WS_URL || 'ws://localhost:8000/ws';
  62. // 控制台调试开关:生产环境关闭,避免多余日志
  63. const shouldLogDebug = false;
  64. const debugLog = (...args: unknown[]) => {
  65. if (!shouldLogDebug) return;
  66. // 使用 console.debug 统一输出调试日志
  67. // eslint-disable-next-line no-console
  68. console.debug(...args);
  69. };
  70. // GIF URL 兜底常量(基础形象)
  71. const FALLBACK_DEFAULT_AVATAR_GIF = getOssUrl('01-Default.gif');
  72. const FALLBACK_POSITIVE_EMOTION_GIF = getOssUrl('04-Positive-emotion.gif');
  73. const FALLBACK_NEGATIVE_EMOTION_GIF = getOssUrl('05-Negative-emotion.gif');
  74. const FALLBACK_TALKING_GIF = getOssUrl('06-talking.gif');
  75. // GIF URL 兜底常量(注册赠送形象:带帽子)
  76. const FALLBACK_REGISTERED_DEFAULT_AVATAR_GIF = getOssUrl('01-Default-Registered.gif');
  77. const FALLBACK_REGISTERED_POSITIVE_EMOTION_GIF = getOssUrl('04-Positive-emotion-Registered.gif');
  78. const FALLBACK_REGISTERED_NEGATIVE_EMOTION_GIF = getOssUrl('05-Negative-emotion-Registered.gif');
  79. const FALLBACK_REGISTERED_TALKING_GIF = getOssUrl('06-talking-Registered.gif');
  80. // 形象 ID 常量(与后端/迁移脚本一致)
  81. const AVATAR_ID_DEFAULT = 'avatar_default';
  82. const AVATAR_ID_REGISTERED = 'avatar_registered_cap';
  83. type AvatarState = 'default' | 'positive' | 'negative' | 'talking';
  84. // 情绪分类函数
  85. const getEmotionCategory = (emotion: string): 'positive' | 'negative' | 'neutral' => {
  86. // 正向情绪
  87. const positiveEmotions = ['happy', 'excited', 'encouraging', 'satisfied', 'friendly'];
  88. // 反向情绪
  89. const negativeEmotions = ['sad', 'angry', 'worried', 'confused', 'sorry'];
  90. if (positiveEmotions.includes(emotion)) {
  91. return 'positive';
  92. }
  93. if (negativeEmotions.includes(emotion)) {
  94. return 'negative';
  95. }
  96. // neutral, surprised, thoughtful 等归为中性
  97. return 'neutral';
  98. };
  99. // 获取情绪 GIF 播放时长(毫秒)
  100. // 统一:正向 2050ms,负向 4290ms(与形象无关)
  101. const getEmotionGifDuration = (_avatarId: string | null, emotionCategory: 'positive' | 'negative'): number => {
  102. if (emotionCategory === 'positive') {
  103. return 2050;
  104. }
  105. if (emotionCategory === 'negative') {
  106. return 4290;
  107. }
  108. return 0;
  109. };
  110. export const ChatBotPage = () => {
  111. const navigate = useNavigate();
  112. const [searchParams] = useSearchParams();
  113. const location = useLocation();
  114. const {
  115. currentState,
  116. currentRequestId,
  117. conversationProgress,
  118. progressLoopCount,
  119. setState,
  120. setRequestId,
  121. setEmotion,
  122. setRecognizedText,
  123. setError,
  124. setConnected,
  125. setProgress,
  126. reset,
  127. isConnected,
  128. } = useAppStore();
  129. const recorderRef = useRef<AudioRecorder | null>(null);
  130. const playerRef = useRef<AudioPlayer | null>(null);
  131. const wsRef = useRef<WebSocketManager | null>(null);
  132. const chunkIndexRef = useRef(0);
  133. const connectionLostRef = useRef(false);
  134. // 首句 greeting 请求 ID(来自后端的 greeting_xxx)
  135. const greetingRequestIdRef = useRef<string | null>(null);
  136. // 标记首句是否处于“可播放/可显示”状态;一旦用户开始录音则置为 true,后续 greeting 全部丢弃
  137. const greetingSuppressedRef = useRef(false);
  138. // 标记当前是否正在播放首句音频,便于在开始录音时精确打断
  139. const isGreetingActiveRef = useRef(false);
  140. const activeRequestIdRef = useRef<string | null>(null);
  141. const cancelledRequestIdsRef = useRef<Set<string>>(new Set());
  142. const mobileAudioPreparedRef = useRef(false);
  143. const sendTimeRef = useRef<number>(0);
  144. const audioWaveRef = useRef<AudioWaveHandle | null>(null);
  145. const isMountedRef = useRef(true);
  146. const [userLevelValue, setUserLevelValue] = useState(() => getUserLevel());
  147. const levelRedirectRef = useRef(false);
  148. const [hasSharedAvatar, setHasSharedAvatarState] = useState(() => getHasSharedAvatar());
  149. // 背景图片 URL
  150. const [backgroundImageUrl, setBackgroundImageUrl] = useState<string | null>(() => {
  151. // 初始化时从 localStorage 获取背景图片 URL
  152. const url = getCurrentBackgroundImageUrl();
  153. return url || null;
  154. });
  155. // 背景图片 ID(只保留 setter,因为变量本身未使用)
  156. const [, setBackgroundImageId] = useState<string | null>(() => {
  157. return getCurrentBackgroundImageId();
  158. });
  159. // 初始化时检查 localStorage,确保第一次打开时立即显示提示
  160. const [showTapToChat, setShowTapToChat] = useState(() => {
  161. const hasShown = getStorage(STORAGE_KEYS.HAS_SHOWN_TAP_TO_CHAT);
  162. // 如果已经显示过,直接返回 false
  163. if (hasShown) {
  164. return false;
  165. }
  166. // 第一次打开,返回 true(但不立即保存到 localStorage,等 WebSocket 连接成功后再保存)
  167. return true;
  168. });
  169. const sendingTimeoutRef = useRef<number | null>(null);
  170. const updateRequestId = useCallback(
  171. (id: string | null) => {
  172. activeRequestIdRef.current = id;
  173. setRequestId(id);
  174. },
  175. [setRequestId]
  176. );
  177. useEffect(() => {
  178. activeRequestIdRef.current = currentRequestId;
  179. }, [currentRequestId]);
  180. useEffect(() => {
  181. const isLoggedIn = getStorage(STORAGE_KEYS.IS_LOGGED_IN) === 'true';
  182. if (!isLoggedIn && userLevelValue >= 5 && !levelRedirectRef.current) {
  183. levelRedirectRef.current = true;
  184. // 等待音频播放完成后再跳转
  185. const performRedirect = async () => {
  186. // 检查是否正在等待AI回复(sending状态)或正在播放音频(playing状态)
  187. const isWaitingOrPlaying = currentState === 'sending' || currentState === 'playing';
  188. const hasActiveRequest = currentRequestId !== null;
  189. const isAudioPlaying = playerRef.current?.isPlaying() || false;
  190. if (isWaitingOrPlaying || hasActiveRequest || isAudioPlaying) {
  191. debugLog('[ChatBotPage] 检测到正在等待AI回复或播放音频,等待完成后再跳转...', {
  192. state: currentState,
  193. hasRequest: hasActiveRequest,
  194. isPlaying: isAudioPlaying
  195. });
  196. // 如果正在等待回复(sending状态),等待状态变为playing或idle
  197. if (currentState === 'sending' || hasActiveRequest) {
  198. await new Promise<void>((resolve) => {
  199. // 设置超时保护,最多等待30秒
  200. const timeoutId = setTimeout(() => {
  201. console.warn('[ChatBotPage] 等待AI回复超时,继续执行跳转');
  202. resolve();
  203. }, 30000);
  204. // 使用轮询检查状态,直到状态变为idle且没有活跃请求
  205. const checkInterval = setInterval(() => {
  206. const appState = useAppStore.getState();
  207. // 如果状态变为idle且没有活跃请求,说明对话已完成
  208. if (appState.currentState === 'idle' && appState.currentRequestId === null) {
  209. clearInterval(checkInterval);
  210. clearTimeout(timeoutId);
  211. resolve();
  212. }
  213. }, 100);
  214. });
  215. }
  216. // 如果音频正在播放或状态为playing,等待播放完成
  217. if (currentState === 'playing' || isAudioPlaying || playerRef.current?.isPlaying()) {
  218. if (playerRef.current) {
  219. try {
  220. await playerRef.current.waitForPlaybackComplete();
  221. debugLog('[ChatBotPage] 音频播放完成');
  222. } catch (error) {
  223. console.warn('[ChatBotPage] 等待音频播放完成时出错:', error);
  224. }
  225. }
  226. }
  227. debugLog('[ChatBotPage] 所有等待完成,执行跳转');
  228. }
  229. navigate('/level5-welcome');
  230. };
  231. performRedirect();
  232. }
  233. }, [userLevelValue, navigate, currentState, currentRequestId]);
  234. const [showCancelTooltip, setShowCancelTooltip] = useState(false);
  235. const [showSendTooltip, setShowSendTooltip] = useState(false);
  236. const [showProgressBarTooltip, setShowProgressBarTooltip] = useState(false);
  237. const [showMissionStoneModal, setShowMissionStoneModal] = useState(false);
  238. const [energyStoneModalType, setEnergyStoneModalType] = useState<'mission' | 'conversation'>('mission');
  239. const [hasClickedMissionStone, setHasClickedMissionStone] = useState(() => {
  240. return getStorage(STORAGE_KEYS.HAS_CLICKED_MISSION_STONE) === 'true';
  241. });
  242. const [hasClickedConversationStone, setHasClickedConversationStone] = useState(() => {
  243. return getStorage(STORAGE_KEYS.HAS_CLICKED_CONVERSATION_STONE) === 'true';
  244. });
  245. const [hasShownProgressBarTooltip, setHasShownProgressBarTooltip] = useState(() => {
  246. const stored = getStorage(STORAGE_KEYS.HAS_SHOWN_PROGRESS_BAR_TOOLTIP);
  247. return stored === 'true';
  248. });
  249. const progressBarTooltipTimerRef = useRef<number | null>(null);
  250. const progressBarTooltipRef = useRef<HTMLImageElement | null>(null);
  251. const pendingStoneIdRef = useRef<string | null>(null);
  252. const [isAvatarCUnlocked, setIsAvatarCUnlocked] = useState(() => {
  253. const stored = getStorage(STORAGE_KEYS.AVATAR_C_UNLOCKED);
  254. return stored === 'true';
  255. });
  256. const avatarCUnlockedRef = useRef(isAvatarCUnlocked);
  257. useEffect(() => {
  258. avatarCUnlockedRef.current = isAvatarCUnlocked;
  259. }, [isAvatarCUnlocked]);
  260. // 累计总说话时长(仅作为从后端同步后的本地缓存,进度和解锁逻辑均以后端为准)
  261. const totalSpeechDurationRef = useRef<number>(
  262. isAvatarCUnlocked ? AVATAR_C_UNLOCK_THRESHOLD_MS : 0
  263. );
  264. // 控制声纹容器高度(延迟降低,等待衰减动画完成)
  265. const [shouldExpandWaveform, setShouldExpandWaveform] = useState(false);
  266. const waveformCollapseTimerRef = useRef<number | null>(null);
  267. const WAVEFORM_HEIGHT_PX = 40;
  268. const waveformHeightStyle = '40PX'; // 始终保持 40PX,不随屏幕尺寸变化
  269. const waveformHeightPx = WAVEFORM_HEIGHT_PX;
  270. // 用于动画的显示进度(平滑过渡)
  271. const [displayProgress, setDisplayProgress] = useState(0);
  272. const animationFrameRef = useRef<number>();
  273. const totalProgressRef = useRef(0);
  274. // 默认置为 true,避免组件初次挂载或路由返回时尚未完成数据同步就触发历史进度动画。
  275. const shouldSkipProgressAnimationRef = useRef(true);
  276. // 保存上一次的进度状态,用于计算动画起始值
  277. const prevProgressStateRef = useRef<{ progress: number; loopCount: number }>({
  278. progress: 0,
  279. loopCount: 0,
  280. });
  281. const recordingTimerRef = useRef<number | null>(null);
  282. const recordingDeadlineRef = useRef<number>(0);
  283. const handleSendRef = useRef<() => void>();
  284. const [remainingTimeMs, setRemainingTimeMs] = useState<number | null>(null);
  285. const pushFrequencyFrame = useCallback((frame: FrequencyFrame) => {
  286. audioWaveRef.current?.pushFrequencyFrame(frame.frequency);
  287. }, []);
  288. const resetFrequencyVisualization = useCallback(() => {
  289. audioWaveRef.current?.pushFrequencyFrame(null);
  290. }, []);
  291. // V2: 完全计算式布局系统
  292. const [layout, setLayout] = useState<CalculatedLayout>(() => {
  293. const initialLayout = calculateLayout();
  294. return initialLayout;
  295. });
  296. // GIF 切换定时器(情绪 GIF 播放一次后切回 talking/default)
  297. const emotionGifTimerRef = useRef<number | null>(null);
  298. // 待处理情绪缓存:收到 emotion 消息时先缓存,等音频真正开始播放时再驱动情绪动画
  299. const pendingEmotionRef = useRef<string | null>(null);
  300. const handleAvatarClick = useCallback(async () => {
  301. if (!isAvatarCUnlocked) {
  302. return;
  303. }
  304. const isLoggedIn = getStorage(STORAGE_KEYS.IS_LOGGED_IN) === 'true';
  305. if (isLoggedIn) {
  306. // 已登录:跳转到 profile 界面
  307. navigate('/profile');
  308. return;
  309. }
  310. // 未登录:根据用户等级跳转
  311. if (userLevelValue >= 5) {
  312. levelRedirectRef.current = true;
  313. // 等待音频播放完成后再跳转
  314. if (playerRef.current?.isPlaying()) {
  315. debugLog('[ChatBotPage] 检测到音频正在播放,等待播放完成后再跳转...');
  316. try {
  317. await playerRef.current.waitForPlaybackComplete();
  318. debugLog('[ChatBotPage] 音频播放完成,执行跳转');
  319. } catch (error) {
  320. console.warn('[ChatBotPage] 等待音频播放完成时出错:', error);
  321. }
  322. }
  323. navigate('/level5-welcome');
  324. return;
  325. }
  326. navigate('/level34-welcome');
  327. }, [isAvatarCUnlocked, navigate, userLevelValue]);
  328. const handleAvatarKeyDown = useCallback(
  329. (event: KeyboardEvent<HTMLDivElement>) => {
  330. if (event.key === 'Enter' || event.key === ' ') {
  331. event.preventDefault();
  332. handleAvatarClick();
  333. }
  334. },
  335. [handleAvatarClick],
  336. );
  337. const timingRef = useRef({
  338. recordStart: 0,
  339. recordEnd: 0,
  340. firstAudioReceived: 0,
  341. emotionReceived: 0,
  342. });
  343. // 使用 Web Animations API 驱动飞行动画,避免部分端 CSS 动画被覆盖
  344. const runStoneAnimation = useCallback(
  345. (container: HTMLElement | null, dx: number, dy: number) => {
  346. if (!container) return;
  347. const img = container.querySelector('.energy-stone') as HTMLElement | null;
  348. const keyframes: Keyframe[] = [
  349. {
  350. transform: 'translate(-50%, -50%) translate3d(0, 0, 0)',
  351. opacity: 1,
  352. offset: 0,
  353. },
  354. {
  355. transform: `translate(-50%, -50%) translate3d(${dx}px, ${dy}px, 0)`,
  356. opacity: 1,
  357. offset: 0.85,
  358. },
  359. {
  360. transform: `translate(-50%, -50%) translate3d(${dx}px, ${dy}px, 0)`,
  361. opacity: 0,
  362. offset: 1,
  363. },
  364. ];
  365. const timing: KeyframeAnimationOptions = {
  366. duration: 1400,
  367. easing: 'ease-in-out',
  368. fill: 'forwards',
  369. };
  370. try {
  371. container.animate(keyframes, timing);
  372. if (img) {
  373. img.animate(
  374. [
  375. { transform: 'translate(-50%, -50%)', opacity: 1, offset: 0 },
  376. { transform: 'translate(-50%, -50%)', opacity: 1, offset: 0.85 },
  377. { transform: 'translate(-50%, -50%)', opacity: 0, offset: 1 },
  378. ],
  379. timing
  380. );
  381. }
  382. } catch (error) {
  383. // 如果 WAAPI 不可用,忽略,保留 CSS 动画兜底
  384. console.warn('[EnergyStone] WAAPI animate failed, fallback to CSS animation', error);
  385. }
  386. },
  387. []
  388. );
  389. // 当前形象ID(支持后端返回/本地缓存)
  390. const [currentAvatarId, setCurrentAvatarId] = useState<string | null>(() => {
  391. return getStorage(STORAGE_KEYS.CURRENT_AVATAR_ID);
  392. });
  393. const [avatarGifSets, setAvatarGifSets] = useState<Record<string, AvatarGifSet>>({
  394. [AVATAR_ID_DEFAULT]: {
  395. default: FALLBACK_DEFAULT_AVATAR_GIF,
  396. positive: FALLBACK_POSITIVE_EMOTION_GIF,
  397. negative: FALLBACK_NEGATIVE_EMOTION_GIF,
  398. talking: FALLBACK_TALKING_GIF,
  399. },
  400. [AVATAR_ID_REGISTERED]: {
  401. default: FALLBACK_REGISTERED_DEFAULT_AVATAR_GIF,
  402. positive: FALLBACK_REGISTERED_POSITIVE_EMOTION_GIF,
  403. negative: FALLBACK_REGISTERED_NEGATIVE_EMOTION_GIF,
  404. talking: FALLBACK_REGISTERED_TALKING_GIF,
  405. },
  406. });
  407. const resolveAvatarGifSet = useCallback(
  408. (avatarId: string | null | undefined): AvatarGifSet => {
  409. const fallback = avatarGifSets[AVATAR_ID_DEFAULT];
  410. if (!avatarId) {
  411. debugLog(`[resolveAvatarGifSet] avatarId 为 null,返回默认形象`);
  412. return fallback;
  413. }
  414. const set = avatarGifSets[avatarId];
  415. const result = {
  416. default: set?.default || fallback.default,
  417. positive: set?.positive || fallback.positive,
  418. negative: set?.negative || fallback.negative,
  419. talking: set?.talking || fallback.talking,
  420. };
  421. debugLog(`[resolveAvatarGifSet] avatarId=${avatarId}, set存在=${!!set}, result=`, result);
  422. return result;
  423. },
  424. [avatarGifSets],
  425. );
  426. const avatarGifSet = useMemo(() => {
  427. const gifSet = resolveAvatarGifSet(currentAvatarId);
  428. debugLog(`[avatarGifSet] currentAvatarId=${currentAvatarId}, gifSet=`, gifSet);
  429. return gifSet;
  430. }, [currentAvatarId, resolveAvatarGifSet]);
  431. const [currentAvatarGif, setCurrentAvatarGif] = useState<string>(() => {
  432. const storedId = getStorage(STORAGE_KEYS.CURRENT_AVATAR_ID);
  433. return resolveAvatarGifSet(storedId).default;
  434. });
  435. const setGifByState = useCallback(
  436. (state: AvatarState) => {
  437. // 实时获取最新的 avatarGifSet,避免闭包问题
  438. const latestAvatarId = getStorage(STORAGE_KEYS.CURRENT_AVATAR_ID);
  439. // 使用最新的 avatarGifSets 状态来计算 GIF
  440. const fallback = avatarGifSets[AVATAR_ID_DEFAULT];
  441. let latestGifSet: AvatarGifSet;
  442. if (!latestAvatarId) {
  443. latestGifSet = fallback;
  444. } else {
  445. const set = avatarGifSets[latestAvatarId];
  446. latestGifSet = {
  447. default: set?.default || fallback.default,
  448. positive: set?.positive || fallback.positive,
  449. negative: set?.negative || fallback.negative,
  450. talking: set?.talking || fallback.talking,
  451. };
  452. }
  453. const nextGif = latestGifSet[state] || latestGifSet.default;
  454. debugLog(`[setGifByState] state=${state}, currentAvatarId=${currentAvatarId}, latestAvatarId=${latestAvatarId}, nextGif=${nextGif}`);
  455. setCurrentAvatarGif(nextGif);
  456. },
  457. [avatarGifSet, currentAvatarId, avatarGifSets],
  458. );
  459. const showDefaultGif = useCallback(() => setGifByState('default'), [setGifByState]);
  460. const showPositiveGif = useCallback(() => setGifByState('positive'), [setGifByState]);
  461. const showNegativeGif = useCallback(() => setGifByState('negative'), [setGifByState]);
  462. const showTalkingGif = useCallback(() => setGifByState('talking'), [setGifByState]);
  463. // 预加载动画形象的 GIF
  464. const preloadAvatarGifs = useCallback(
  465. (avatarId: string | null) => {
  466. const gifSet = resolveAvatarGifSet(avatarId);
  467. const gifUrls = [gifSet.default, gifSet.positive, gifSet.negative, gifSet.talking];
  468. // 使用 Image 对象预加载所有 GIF
  469. gifUrls.forEach((url) => {
  470. if (url) {
  471. const img = new Image();
  472. img.src = url;
  473. // 静默处理加载错误,避免影响主流程
  474. img.onerror = () => {
  475. console.warn(`[预加载] GIF 加载失败: ${url}`);
  476. };
  477. }
  478. });
  479. debugLog(`[预加载] 已开始预加载形象 ${avatarId || 'default'} 的所有 GIF`);
  480. },
  481. [resolveAvatarGifSet]
  482. );
  483. // 拉取头像 GIF 配置
  484. useEffect(() => {
  485. const fetchAvatarGifs = async () => {
  486. try {
  487. const res = await getAvatarGifs();
  488. if (!res.success || !res.data) {
  489. return;
  490. }
  491. setAvatarGifSets((prev) => {
  492. const next = { ...prev };
  493. const applyPartial = (key: string, partial?: Partial<AvatarGifSet>) => {
  494. if (!partial) return;
  495. const base = next[key] || prev[AVATAR_ID_DEFAULT];
  496. next[key] = {
  497. default: partial.default || base.default,
  498. positive: partial.positive || base.positive,
  499. negative: partial.negative || base.negative,
  500. talking: partial.talking || base.talking,
  501. };
  502. };
  503. applyPartial(AVATAR_ID_DEFAULT, res.data.avatar_default);
  504. applyPartial(AVATAR_ID_REGISTERED, res.data.avatar_registered_cap);
  505. return next;
  506. });
  507. } catch (error) {
  508. // 静默降级使用兜底
  509. console.warn('获取头像 GIF 配置失败,使用兜底资源', error);
  510. }
  511. };
  512. fetchAvatarGifs();
  513. }, []);
  514. // 当 avatarGifSets 更新或 currentAvatarId 变化时,预加载当前形象的 GIF
  515. useEffect(() => {
  516. if (Object.keys(avatarGifSets).length > 0) {
  517. // 如果 currentAvatarId 为 null,预加载默认形象
  518. const avatarIdToPreload = currentAvatarId || AVATAR_ID_DEFAULT;
  519. preloadAvatarGifs(avatarIdToPreload);
  520. }
  521. }, [avatarGifSets, currentAvatarId, preloadAvatarGifs]);
  522. // 监听 storage(跨标签页同步当前形象)
  523. useEffect(() => {
  524. const handleStorage = (event: StorageEvent) => {
  525. if (event.key === STORAGE_KEYS.CURRENT_AVATAR_ID) {
  526. setCurrentAvatarId(event.newValue);
  527. }
  528. if (event.key === STORAGE_KEYS.IS_LOGGED_IN && event.newValue === 'false') {
  529. // 游客回退默认形象
  530. setCurrentAvatarId(AVATAR_ID_DEFAULT);
  531. }
  532. };
  533. window.addEventListener('storage', handleStorage);
  534. return () => {
  535. window.removeEventListener('storage', handleStorage);
  536. };
  537. }, []);
  538. // 监听路由变化,同步 localStorage 中的 currentAvatarId(处理从其他页面返回的情况)
  539. useEffect(() => {
  540. if (location.pathname === '/chatbot') {
  541. const storedAvatarId = getStorage(STORAGE_KEYS.CURRENT_AVATAR_ID);
  542. // 只有当 localStorage 中的值与当前状态不一致时才更新
  543. if (storedAvatarId !== currentAvatarId) {
  544. debugLog(`[ChatBotPage] 检测到 localStorage 中的形象ID变化: ${currentAvatarId} -> ${storedAvatarId}`);
  545. setCurrentAvatarId(storedAvatarId);
  546. // 立即更新显示的 GIF,使用最新的 avatarGifSets
  547. const newGifSet = resolveAvatarGifSet(storedAvatarId);
  548. debugLog(`[ChatBotPage] 更新显示的 GIF: ${newGifSet.default}`);
  549. setCurrentAvatarGif(newGifSet.default);
  550. }
  551. }
  552. // eslint-disable-next-line react-hooks/exhaustive-deps
  553. }, [location.pathname]);
  554. // 当形象变化时立即更新显示 GIF
  555. useEffect(() => {
  556. showDefaultGif();
  557. }, [avatarGifSet, showDefaultGif]);
  558. const syncUserLevel = useCallback((level: number) => {
  559. setUserLevel(level);
  560. setUserLevelValue(level);
  561. }, []);
  562. const unlockAvatarC = useCallback(() => {
  563. if (avatarCUnlockedRef.current) {
  564. return;
  565. }
  566. avatarCUnlockedRef.current = true;
  567. setIsAvatarCUnlocked(true);
  568. setStorage(STORAGE_KEYS.AVATAR_C_UNLOCKED, 'true');
  569. const userId = getUserId();
  570. if (userId) {
  571. updateUserUIState(userId, {
  572. avatar_c_unlocked: true,
  573. }).catch(() => {
  574. // 同步失败不影响主流程
  575. });
  576. }
  577. }, []);
  578. const emitStoneEvent = useCallback(
  579. (stoneId: string, event: 'click' | 'timeout', position: EnergyStoneEventPayload) => {
  580. if (!wsRef.current) {
  581. return;
  582. }
  583. wsRef.current.send({
  584. type: 'energy_stone_event',
  585. requestId: stoneId,
  586. stoneId,
  587. event,
  588. clientTs: Date.now(),
  589. position,
  590. });
  591. },
  592. []
  593. );
  594. const resolveStoneSize = useCallback(
  595. (_stoneType: 'mission' | 'conversation') => {
  596. // 设计稿统一尺寸 48px,基于 vw/vh 最小值
  597. return 48;
  598. },
  599. []
  600. );
  601. // 创建一个隐藏的容器元素用于 useEnergyStones hook 计算位置
  602. const hiddenEnergyStoneZoneRef = useRef<HTMLDivElement>(null);
  603. const { stones: energyStones, spawnStone, handleStoneClick } = useEnergyStones(hiddenEnergyStoneZoneRef, {
  604. onEvent: emitStoneEvent,
  605. resolveStoneSize,
  606. });
  607. // 当能量石开始消失时,设置动画的起点和终点(处理超时自动消失的情况)
  608. useEffect(() => {
  609. const timers: number[] = [];
  610. const resetAnimation = (element?: HTMLElement | null) => {
  611. if (!element) {
  612. return;
  613. }
  614. element.style.animation = 'none';
  615. // 强制重排,确保重新读取起点坐标
  616. void element.offsetWidth;
  617. element.style.animation = '';
  618. };
  619. energyStones.forEach((stone) => {
  620. const container = document.querySelector(
  621. `[data-stone-id="${stone.stoneId}"]`
  622. ) as HTMLElement | null;
  623. // 非消失状态,移除就绪标记,避免错误启动动画
  624. if (!stone.fading) {
  625. container?.removeAttribute('data-anim-ready');
  626. return;
  627. }
  628. // 使用 setTimeout 确保 DOM 已更新
  629. const timer = window.setTimeout(() => {
  630. const target = document.querySelector(
  631. `[data-stone-id="${stone.stoneId}"]`
  632. ) as HTMLElement | null;
  633. if (!target) {
  634. return;
  635. }
  636. const rect = target.getBoundingClientRect();
  637. const startLeft = rect.left + rect.width / 2; // 中心点 x 坐标(像素)
  638. const startTop = rect.top + rect.height / 2; // 中心点 y 坐标(像素)
  639. // 计算终点位置(动画形象中心,距离顶部60%位置)
  640. const viewportWidth = window.innerWidth;
  641. const viewportHeight = window.innerHeight;
  642. // 计算终点 top 位置(像素)
  643. const endTopPx = Math.min(
  644. (452 * Math.min(viewportWidth, 600) / 375),
  645. (452 / 812) * viewportHeight
  646. );
  647. const endLeft = viewportWidth / 2; // 50% 位置(像素)
  648. const dx = endLeft - startLeft;
  649. const dy = endTopPx - startTop;
  650. // 设置 CSS 变量,用于动画(使用像素值)
  651. target.style.setProperty('--animation-start-left', `${startLeft}px`);
  652. target.style.setProperty('--animation-start-top', `${startTop}px`);
  653. target.style.setProperty('--animation-end-left', `${endLeft}px`);
  654. target.style.setProperty('--animation-end-top', `${endTopPx}px`);
  655. target.style.setProperty('--animation-dx', `${dx}px`);
  656. target.style.setProperty('--animation-dy', `${dy}px`);
  657. // 强制写入动画样式,避免某些终端上样式覆盖/未生效
  658. target.style.left = `${startLeft}px`;
  659. target.style.top = `${startTop}px`;
  660. target.style.transform = 'translate(-50%, -50%) translate3d(0, 0, 0)';
  661. target.style.animation = 'energyStoneMoveToAvatar 1s ease-in-out forwards';
  662. target.style.willChange = 'transform, opacity';
  663. target.style.position = 'fixed';
  664. target.style.pointerEvents = 'none';
  665. runStoneAnimation(target, dx, dy);
  666. // 标记动画就绪,允许 CSS 启动
  667. target.setAttribute('data-anim-ready', 'true');
  668. // 重新启动动画,确保使用更新后的起点
  669. resetAnimation(target);
  670. resetAnimation(target.querySelector('.energy-stone') as HTMLElement | null);
  671. resetAnimation(target.querySelector('.energy-stone-hint') as HTMLElement | null);
  672. }, 0);
  673. timers.push(timer);
  674. });
  675. return () => {
  676. timers.forEach((timer) => {
  677. window.clearTimeout(timer);
  678. });
  679. };
  680. }, [energyStones, runStoneAnimation]);
  681. const startStoneAnimationAndRemove = useCallback(
  682. (stoneId: string) => {
  683. const container = document.querySelector(
  684. `[data-stone-id="${stoneId}"]`
  685. ) as HTMLElement | null;
  686. if (container) {
  687. const rect = container.getBoundingClientRect();
  688. const startLeft = rect.left + rect.width / 2;
  689. const startTop = rect.top + rect.height / 2;
  690. const viewportWidth = window.innerWidth;
  691. const viewportHeight = window.innerHeight;
  692. const endTopPx = Math.min(
  693. (452 * Math.min(viewportWidth, 600) / 375),
  694. (452 / 812) * viewportHeight
  695. );
  696. const endLeft = viewportWidth / 2;
  697. const dx = endLeft - startLeft;
  698. const dy = endTopPx - startTop;
  699. container.style.setProperty('--animation-start-left', `${startLeft}px`);
  700. container.style.setProperty('--animation-start-top', `${startTop}px`);
  701. container.style.setProperty('--animation-end-left', `${endLeft}px`);
  702. container.style.setProperty('--animation-end-top', `${endTopPx}px`);
  703. container.style.setProperty('--animation-dx', `${dx}px`);
  704. container.style.setProperty('--animation-dy', `${dy}px`);
  705. container.style.left = `${startLeft}px`;
  706. container.style.top = `${startTop}px`;
  707. container.style.transform = 'translate(-50%, -50%) translate3d(0, 0, 0)';
  708. container.style.animation = 'energyStoneMoveToAvatar 1s ease-in-out forwards';
  709. container.style.willChange = 'transform, opacity';
  710. container.style.position = 'fixed';
  711. container.style.pointerEvents = 'none';
  712. runStoneAnimation(container, dx, dy);
  713. }
  714. handleStoneClick(stoneId);
  715. },
  716. [handleStoneClick, runStoneAnimation]
  717. );
  718. const handleMissionStoneModalClose = useCallback(() => {
  719. setShowMissionStoneModal(false);
  720. const pendingStoneId = pendingStoneIdRef.current;
  721. if (pendingStoneId) {
  722. pendingStoneIdRef.current = null;
  723. startStoneAnimationAndRemove(pendingStoneId);
  724. }
  725. }, [startStoneAnimationAndRemove]);
  726. // 能量石展示区域:宽高 & 位置按设计稿 375×812 固定,以 px2vw/px2vh/px2vmin 适配
  727. const stopRecordingTimer = useCallback((options?: { preserveCountdown?: boolean }) => {
  728. if (recordingTimerRef.current) {
  729. clearInterval(recordingTimerRef.current);
  730. recordingTimerRef.current = null;
  731. }
  732. recordingDeadlineRef.current = 0;
  733. if (!options?.preserveCountdown) {
  734. setRemainingTimeMs(null);
  735. }
  736. }, []);
  737. const startRecordingTimer = useCallback(() => {
  738. stopRecordingTimer();
  739. recordingDeadlineRef.current = Date.now() + MAX_RECORDING_DURATION_MS;
  740. setRemainingTimeMs(MAX_RECORDING_DURATION_MS);
  741. recordingTimerRef.current = window.setInterval(() => {
  742. const remaining = recordingDeadlineRef.current - Date.now();
  743. if (remaining <= 0) {
  744. setRemainingTimeMs(0);
  745. stopRecordingTimer({ preserveCountdown: true });
  746. if (useAppStore.getState().currentState === 'recording') {
  747. handleSendRef.current?.();
  748. }
  749. return;
  750. }
  751. setRemainingTimeMs(remaining);
  752. }, 250);
  753. }, [stopRecordingTimer]);
  754. useEffect(() => {
  755. return () => {
  756. stopRecordingTimer();
  757. };
  758. }, [stopRecordingTimer]);
  759. useEffect(() => {
  760. if (currentState !== 'recording') {
  761. stopRecordingTimer();
  762. }
  763. }, [currentState, stopRecordingTimer]);
  764. const formatCountdown = (ms: number) => {
  765. const totalSeconds = Math.max(0, Math.ceil(ms / 1000));
  766. const minutes = Math.floor(totalSeconds / 60);
  767. const seconds = totalSeconds % 60;
  768. return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
  769. };
  770. // 进度动画效果(支持多圈连续动画)
  771. useEffect(() => {
  772. const targetTotal = progressLoopCount * 100 + conversationProgress;
  773. // 🔍 日志:记录 useEffect 触发时的状态
  774. debugLog('[Progress] [useEffect] 触发:', {
  775. conversationProgress,
  776. progressLoopCount,
  777. targetTotal,
  778. prevProgressStateRef: { ...prevProgressStateRef.current },
  779. totalProgressRef: totalProgressRef.current,
  780. displayProgress,
  781. shouldSkipAnimation: shouldSkipProgressAnimationRef.current,
  782. hasActiveAnimation: !!animationFrameRef.current,
  783. });
  784. // 🔧 如果 shouldSkipProgressAnimation 为 true,说明处于初始化/同步阶段
  785. // 直接同步 ref 并返回,避免播放历史动画。标志由后续用户动作(如 handleSend)再置为 false。
  786. if (shouldSkipProgressAnimationRef.current) {
  787. debugLog('[Progress] [useEffect] 初始化/同步阶段,跳过动画并同步 ref');
  788. if (animationFrameRef.current) {
  789. cancelAnimationFrame(animationFrameRef.current);
  790. animationFrameRef.current = undefined;
  791. }
  792. prevProgressStateRef.current = {
  793. progress: conversationProgress,
  794. loopCount: progressLoopCount,
  795. };
  796. totalProgressRef.current = targetTotal;
  797. const normalized = ((targetTotal % 100) + 100) % 100;
  798. setDisplayProgress(normalized);
  799. return;
  800. }
  801. // 使用上一次保存的状态值作为起始值(确保动画起始值正确)
  802. // 这样可以避免 displayProgress 异步更新导致的时序问题
  803. let prevTotal = prevProgressStateRef.current.loopCount * 100 + prevProgressStateRef.current.progress;
  804. // 立即保存当前状态到 prevProgressStateRef(供下次动画使用)
  805. // 这样即使本次动画还没完成,新的状态更新也能正确工作
  806. const currentState = {
  807. progress: conversationProgress,
  808. loopCount: progressLoopCount,
  809. };
  810. // 如果 prevTotal 是初始值 0,但目标值已经大于 0,说明是首次使用或状态被重置
  811. // 此时应该使用 totalProgressRef.current 或 displayProgress 作为起始值
  812. // 但如果 shouldSkipProgressAnimation 为 true,说明是初始化,应该直接使用目标值作为起始值
  813. if (prevTotal === 0 && targetTotal > 0) {
  814. if (shouldSkipProgressAnimationRef.current) {
  815. // 初始化场景:直接使用目标值作为起始值,避免播放动画
  816. debugLog('[Progress] [useEffect] 初始化场景,使用目标值作为起始值,跳过动画');
  817. prevTotal = targetTotal;
  818. prevProgressStateRef.current = currentState;
  819. totalProgressRef.current = targetTotal;
  820. } else {
  821. debugLog('[Progress] [useEffect] 检测到初始值情况,使用 displayProgress 或 totalProgressRef');
  822. // 如果 totalProgressRef 有值,使用它;否则使用 displayProgress
  823. if (totalProgressRef.current > 0) {
  824. prevTotal = totalProgressRef.current;
  825. debugLog('[Progress] [useEffect] 使用 totalProgressRef:', totalProgressRef.current);
  826. } else {
  827. prevTotal = displayProgress;
  828. debugLog('[Progress] [useEffect] 使用 displayProgress:', displayProgress);
  829. }
  830. // 更新 prevProgressStateRef 为当前显示的状态
  831. prevProgressStateRef.current = {
  832. progress: displayProgress,
  833. loopCount: Math.floor(totalProgressRef.current / 100),
  834. };
  835. debugLog('[Progress] [useEffect] 更新 prevProgressStateRef 为:', prevProgressStateRef.current);
  836. }
  837. }
  838. // 始终使用上一次保存的状态作为起始值,而不是 totalProgressRef.current
  839. // 因为 totalProgressRef.current 可能在动画过程中,不准确
  840. let startTotal = prevTotal;
  841. // 如果 totalProgressRef 与上一次状态不一致,同步它
  842. // 这样可以确保 totalProgressRef 与起始值一致,避免动画跳变
  843. if (!shouldSkipProgressAnimationRef.current) {
  844. const diffFromPrev = Math.abs(totalProgressRef.current - prevTotal);
  845. debugLog('[Progress] [useEffect] 检查 totalProgressRef 同步:', {
  846. diffFromPrev,
  847. totalProgressRef: totalProgressRef.current,
  848. prevTotal,
  849. needSync: diffFromPrev > 1,
  850. });
  851. // 如果差异较大(超过1%),说明可能有动画在进行,需要取消它并同步起始值
  852. if (diffFromPrev > 1) {
  853. debugLog('[Progress] [useEffect] 取消旧动画并同步 totalProgressRef');
  854. // 取消可能正在进行的动画
  855. if (animationFrameRef.current) {
  856. cancelAnimationFrame(animationFrameRef.current);
  857. animationFrameRef.current = undefined;
  858. }
  859. // 同步 totalProgressRef 到起始值
  860. totalProgressRef.current = startTotal;
  861. }
  862. }
  863. // 立即更新 prevProgressStateRef 为当前状态(供下次动画使用)
  864. // 注意:这里保存的是本次动画的目标值,下次动画会使用这个值作为起始值
  865. prevProgressStateRef.current = currentState;
  866. const diff = targetTotal - startTotal;
  867. debugLog('[Progress] [useEffect] 计算动画参数:', {
  868. startTotal,
  869. targetTotal,
  870. diff,
  871. willAnimate: Math.abs(diff) >= 0.01 && !shouldSkipProgressAnimationRef.current,
  872. });
  873. // 如果 diff 为 0 或非常小,直接同步,不播放动画
  874. if (Math.abs(diff) < 0.01) {
  875. debugLog('[Progress] [useEffect] 跳过动画(diff 太小):', {
  876. diff,
  877. startTotal,
  878. targetTotal,
  879. });
  880. totalProgressRef.current = targetTotal;
  881. const normalized = ((targetTotal % 100) + 100) % 100;
  882. setDisplayProgress(normalized);
  883. // prevProgressStateRef 已经在上面更新了,这里不需要再次更新
  884. return;
  885. }
  886. // 处理整数圈:如果 diff 接近 0 且是整数圈,播放完整一圈动画
  887. let actualDiff = diff;
  888. if (Math.abs(diff) < 0.1) {
  889. // 判断是否是整数圈(目标值是 100 的整数倍)
  890. const isIntegerLoop = Math.abs(targetTotal % 100) < 0.1;
  891. if (isIntegerLoop && targetTotal > startTotal) {
  892. // 整数圈增长,播放完整一圈动画
  893. actualDiff = 100;
  894. } else if (isIntegerLoop && targetTotal < startTotal) {
  895. // 整数圈减少,播放完整一圈反向动画
  896. actualDiff = -100;
  897. } else {
  898. // 非整数圈的微小变化,直接同步
  899. totalProgressRef.current = targetTotal;
  900. const normalized = ((targetTotal % 100) + 100) % 100;
  901. setDisplayProgress(normalized);
  902. // prevProgressStateRef 已经在上面更新了,这里不需要再次更新
  903. return;
  904. }
  905. }
  906. // 每 1% 的进度约 8ms,限制在 0.4s~2.4s 之间
  907. const durationPerPercent = 8;
  908. const duration = Math.max(400, Math.min(2400, Math.abs(actualDiff) * durationPerPercent));
  909. const startTime = performance.now();
  910. debugLog('[Progress] [useEffect] 开始动画:', {
  911. startTotal,
  912. targetTotal,
  913. actualDiff,
  914. duration,
  915. startTime,
  916. });
  917. if (animationFrameRef.current) {
  918. debugLog('[Progress] [useEffect] 取消旧动画');
  919. cancelAnimationFrame(animationFrameRef.current);
  920. }
  921. let animationFrameCount = 0;
  922. const animate = (currentTime: number) => {
  923. animationFrameCount++;
  924. const elapsed = currentTime - startTime;
  925. const progress = Math.min(elapsed / duration, 1);
  926. // easeOutCubic 缓动
  927. const easeProgress = 1 - Math.pow(1 - progress, 3);
  928. const currentTotal = startTotal + actualDiff * easeProgress;
  929. totalProgressRef.current = currentTotal;
  930. const normalized = ((currentTotal % 100) + 100) % 100;
  931. setDisplayProgress(normalized);
  932. // 🔍 日志:每10帧记录一次动画进度
  933. if (animationFrameCount % 10 === 0 || progress >= 1) {
  934. debugLog('[Progress] [animate] 动画进度:', {
  935. frame: animationFrameCount,
  936. progress: (progress * 100).toFixed(2) + '%',
  937. currentTotal: currentTotal.toFixed(2),
  938. normalized: normalized.toFixed(2),
  939. elapsed: elapsed.toFixed(2) + 'ms',
  940. });
  941. }
  942. if (progress < 1) {
  943. animationFrameRef.current = requestAnimationFrame(animate);
  944. } else {
  945. // 动画完成后,同步到实际的目标值
  946. debugLog('[Progress] [animate] 动画完成:', {
  947. finalTotal: targetTotal,
  948. finalNormalized: ((targetTotal % 100) + 100) % 100,
  949. totalFrames: animationFrameCount,
  950. });
  951. totalProgressRef.current = targetTotal;
  952. const finalNormalized = ((targetTotal % 100) + 100) % 100;
  953. setDisplayProgress(finalNormalized);
  954. // prevProgressStateRef 已经在 useEffect 开始时更新了,这里不需要再次更新
  955. }
  956. };
  957. animationFrameRef.current = requestAnimationFrame(animate);
  958. return () => {
  959. if (animationFrameRef.current) {
  960. cancelAnimationFrame(animationFrameRef.current);
  961. }
  962. };
  963. }, [conversationProgress, progressLoopCount]);
  964. // 控制声纹容器高度变化
  965. useEffect(() => {
  966. // 清除之前的定时器
  967. if (waveformCollapseTimerRef.current) {
  968. clearTimeout(waveformCollapseTimerRef.current);
  969. waveformCollapseTimerRef.current = null;
  970. }
  971. if (currentState === 'recording' || currentState === 'playing') {
  972. // 录音或播放时,立即展开
  973. setShouldExpandWaveform(true);
  974. } else {
  975. // 其他状态(sending/idle 等),延迟 3 秒后再收起(等待衰减动画完成)
  976. waveformCollapseTimerRef.current = window.setTimeout(() => {
  977. setShouldExpandWaveform(false);
  978. }, 3000); // 3秒足够让所有竖条衰减为静态高度
  979. }
  980. return () => {
  981. if (waveformCollapseTimerRef.current) {
  982. clearTimeout(waveformCollapseTimerRef.current);
  983. }
  984. };
  985. }, [currentState]);
  986. // 监听录音状态,首次显示取消提示(延迟 2 秒出现)
  987. useEffect(() => {
  988. let timer: number | undefined;
  989. if (currentState === 'recording') {
  990. const hasShownCancel = getStorage(STORAGE_KEYS.HAS_SHOWN_CANCEL_TOOLTIP);
  991. if (!hasShownCancel) {
  992. timer = window.setTimeout(() => {
  993. setShowCancelTooltip(true);
  994. setStorage(STORAGE_KEYS.HAS_SHOWN_CANCEL_TOOLTIP, 'true');
  995. const userId = getUserId();
  996. if (userId) {
  997. updateUserUIState(userId, {
  998. has_shown_cancel_tooltip: true,
  999. }).catch(() => {
  1000. // 同步失败不影响主流程
  1001. });
  1002. }
  1003. }, 200); // 提示更快出现
  1004. } else {
  1005. // 已显示过,确保隐藏
  1006. setShowCancelTooltip(false);
  1007. }
  1008. } else {
  1009. // 非录音状态,隐藏提示
  1010. setShowCancelTooltip(false);
  1011. }
  1012. return () => {
  1013. if (timer !== undefined) {
  1014. window.clearTimeout(timer);
  1015. }
  1016. };
  1017. }, [currentState]);
  1018. // 监听录音状态,首次显示发送提示(延迟 2 秒出现)
  1019. useEffect(() => {
  1020. let timer: number | undefined;
  1021. if (currentState === 'recording') {
  1022. const hasShownSend = getStorage(STORAGE_KEYS.HAS_SHOWN_SEND_TOOLTIP);
  1023. if (!hasShownSend) {
  1024. timer = window.setTimeout(() => {
  1025. setShowSendTooltip(true);
  1026. setStorage(STORAGE_KEYS.HAS_SHOWN_SEND_TOOLTIP, 'true');
  1027. const userId = getUserId();
  1028. if (userId) {
  1029. updateUserUIState(userId, {
  1030. has_shown_send_tooltip: true,
  1031. }).catch(() => {
  1032. // 同步失败不影响主流程
  1033. });
  1034. }
  1035. }, 200); // 提示更快出现
  1036. } else {
  1037. // 已显示过,确保隐藏
  1038. setShowSendTooltip(false);
  1039. }
  1040. } else {
  1041. // 非录音状态,隐藏提示
  1042. setShowSendTooltip(false);
  1043. }
  1044. return () => {
  1045. if (timer !== undefined) {
  1046. window.clearTimeout(timer);
  1047. }
  1048. };
  1049. }, [currentState]);
  1050. const dismissProgressBarTooltip = useCallback(() => {
  1051. if (progressBarTooltipTimerRef.current) {
  1052. clearTimeout(progressBarTooltipTimerRef.current);
  1053. progressBarTooltipTimerRef.current = null;
  1054. }
  1055. if (progressBarTooltipRef.current) {
  1056. progressBarTooltipRef.current.style.opacity = '0';
  1057. progressBarTooltipRef.current.style.pointerEvents = 'none';
  1058. progressBarTooltipRef.current.style.display = 'none';
  1059. }
  1060. setShowProgressBarTooltip(false);
  1061. }, []);
  1062. useEffect(() => {
  1063. if (showProgressBarTooltip && progressBarTooltipRef.current) {
  1064. progressBarTooltipRef.current.style.display = 'block';
  1065. progressBarTooltipRef.current.style.opacity = '1';
  1066. progressBarTooltipRef.current.style.pointerEvents = 'none';
  1067. }
  1068. }, [showProgressBarTooltip]);
  1069. // 监听进度条变化,首次有进度时显示进度条提示(只出现一次)
  1070. useEffect(() => {
  1071. if (
  1072. displayProgress > 0 &&
  1073. !hasShownProgressBarTooltip &&
  1074. isConnected &&
  1075. currentState !== 'recording'
  1076. ) {
  1077. setShowProgressBarTooltip(true);
  1078. setStorage(STORAGE_KEYS.HAS_SHOWN_PROGRESS_BAR_TOOLTIP, 'true');
  1079. setHasShownProgressBarTooltip(true);
  1080. const userId = getUserId();
  1081. if (userId) {
  1082. updateUserUIState(userId, {
  1083. has_shown_progress_bar_tooltip: true,
  1084. }).catch(() => {
  1085. // 同步失败不影响主流程
  1086. });
  1087. }
  1088. }
  1089. }, [displayProgress, hasShownProgressBarTooltip, isConnected, currentState]);
  1090. // 进度条提示显示后自动隐藏(2 秒)
  1091. useEffect(() => {
  1092. if (!showProgressBarTooltip) {
  1093. if (progressBarTooltipTimerRef.current) {
  1094. clearTimeout(progressBarTooltipTimerRef.current);
  1095. progressBarTooltipTimerRef.current = null;
  1096. }
  1097. return;
  1098. }
  1099. progressBarTooltipTimerRef.current = window.setTimeout(() => {
  1100. setShowProgressBarTooltip(false);
  1101. progressBarTooltipTimerRef.current = null;
  1102. }, 2000);
  1103. return () => {
  1104. if (progressBarTooltipTimerRef.current) {
  1105. clearTimeout(progressBarTooltipTimerRef.current);
  1106. progressBarTooltipTimerRef.current = null;
  1107. }
  1108. };
  1109. }, [showProgressBarTooltip]);
  1110. // 录音状态下强制隐藏进度条提示,避免在用户开始录音后残留
  1111. useEffect(() => {
  1112. if (currentState === 'recording') {
  1113. dismissProgressBarTooltip();
  1114. }
  1115. }, [currentState, dismissProgressBarTooltip]);
  1116. // 监听屏幕尺寸变化
  1117. useEffect(() => {
  1118. // 初始化时更新标记
  1119. updateTooSmallFlag();
  1120. const cleanup = onScreenResize(() => {
  1121. const newLayout = calculateLayout();
  1122. setLayout(newLayout); // V2: 更新完全计算式布局
  1123. // 更新 data-too-small 标记
  1124. updateTooSmallFlag();
  1125. });
  1126. return cleanup;
  1127. }, []);
  1128. // 同步背景图片状态的函数
  1129. const syncBackgroundImageState = useCallback(() => {
  1130. const bgUrl = getCurrentBackgroundImageUrl();
  1131. const bgId = getCurrentBackgroundImageId();
  1132. // 直接更新状态,React 会自动处理重复更新
  1133. setBackgroundImageUrl(bgUrl);
  1134. setBackgroundImageId(bgId);
  1135. }, []);
  1136. // 初始化背景图片(从 localStorage 读取)
  1137. useEffect(() => {
  1138. const bgUrl = getCurrentBackgroundImageUrl();
  1139. const bgId = getCurrentBackgroundImageId();
  1140. if (bgUrl) {
  1141. setBackgroundImageUrl(bgUrl);
  1142. }
  1143. if (bgId) {
  1144. setBackgroundImageId(bgId);
  1145. }
  1146. if (!bgUrl || !bgId) {
  1147. // 如果没有背景图片,尝试从用户信息同步
  1148. const user_id = getUserId();
  1149. if (user_id) {
  1150. getUserInfo(user_id).then((userInfo) => {
  1151. if (userInfo.success && userInfo.data?.current_background_image_id) {
  1152. syncBackgroundImageToStorage(
  1153. userInfo.data.current_background_image_id,
  1154. userInfo.data.current_background_image_metadata
  1155. );
  1156. const newBgUrl = getCurrentBackgroundImageUrl();
  1157. const newBgId = getCurrentBackgroundImageId();
  1158. if (newBgUrl) {
  1159. setBackgroundImageUrl(newBgUrl);
  1160. }
  1161. if (newBgId) {
  1162. setBackgroundImageId(newBgId);
  1163. }
  1164. }
  1165. }).catch(() => {
  1166. // 静默处理错误
  1167. });
  1168. }
  1169. }
  1170. }, []);
  1171. // 能量石点击后直接消失,不再需要监听 fading 状态
  1172. // 监听 localStorage 中背景图片的变化
  1173. useEffect(() => {
  1174. // 监听 storage 事件(其他标签页/窗口的变化)
  1175. const handleStorageChange = (e: StorageEvent) => {
  1176. if (e.key === STORAGE_KEYS.CURRENT_BACKGROUND_IMAGE_ID ||
  1177. e.key === STORAGE_KEYS.CURRENT_BACKGROUND_IMAGE_URL) {
  1178. syncBackgroundImageState();
  1179. }
  1180. };
  1181. // 监听页面可见性变化(当页面重新获得焦点时检查)
  1182. const handleVisibilityChange = () => {
  1183. if (!document.hidden) {
  1184. syncBackgroundImageState();
  1185. }
  1186. };
  1187. // 定期检查背景图片变化(作为后备机制,每5秒检查一次)
  1188. const intervalId = setInterval(() => {
  1189. syncBackgroundImageState();
  1190. }, 5000);
  1191. window.addEventListener('storage', handleStorageChange);
  1192. document.addEventListener('visibilitychange', handleVisibilityChange);
  1193. return () => {
  1194. window.removeEventListener('storage', handleStorageChange);
  1195. document.removeEventListener('visibilitychange', handleVisibilityChange);
  1196. clearInterval(intervalId);
  1197. };
  1198. }, [syncBackgroundImageState]);
  1199. // 处理OAuth登录回调(QQ登录成功后直接跳转到chatbot)
  1200. useEffect(() => {
  1201. const oauth = searchParams.get('oauth');
  1202. const userId = searchParams.get('user_id');
  1203. const token = searchParams.get('token');
  1204. // 如果 URL 中有 OAuth 回调参数,说明是登录成功回调
  1205. // ✅ 确保 user_id 和 token 已设置到 localStorage(双重保险,避免时序问题)
  1206. if (oauth === 'qq' && userId) {
  1207. console.log(`[ChatBotPage] 🔧 检测到 QQ OAuth 回调,确保参数已设置到 localStorage - user_id=${userId}, token=${token ? '已提供' : '未提供'}`);
  1208. // 1. 确保用户 ID 已设置(同步操作)
  1209. setStorage(STORAGE_KEYS.USER_ID, userId);
  1210. // 2. 如果 URL 中有 token,确保已设置(同步操作)
  1211. if (token) {
  1212. setUserToken(token);
  1213. console.log(`[ChatBotPage] ✅ 已设置 token 到 localStorage`);
  1214. }
  1215. // 3. 确保登录状态已设置(同步操作)
  1216. setStorage(STORAGE_KEYS.IS_LOGGED_IN, 'true');
  1217. console.log(`[ChatBotPage] ✅ QQ OAuth 回调参数已全部设置到 localStorage`);
  1218. antMessage.success('QQ登录成功');
  1219. // 清除URL参数(延迟清除,确保 UserGuard 能读取到参数)
  1220. setTimeout(() => {
  1221. navigate('/chatbot', { replace: true });
  1222. }, 100);
  1223. }
  1224. }, [searchParams, navigate]);
  1225. // 初始化
  1226. useEffect(() => {
  1227. // 🔧 立即设置 shouldSkipProgressAnimation = true,避免在异步加载完成前触发动画
  1228. // 这可以防止从其他页面返回时播放历史动画
  1229. shouldSkipProgressAnimationRef.current = true;
  1230. debugLog('[Progress] [初始化] 组件挂载,设置 shouldSkipProgressAnimation = true');
  1231. // 记录用户当前所在页面
  1232. setStorage(STORAGE_KEYS.CURRENT_PAGE, 'chatbot');
  1233. // 记录路由访问
  1234. markRouteVisited('/chatbot');
  1235. const visited = getVisitedRoutes();
  1236. const userId = getUserId();
  1237. if (userId) {
  1238. // 从数据库加载所有用户信息到 localStorage
  1239. // 1. 先加载用户基本信息(getUserInfo)
  1240. // 2. 再加载用户 UI 状态(getUserUIState)
  1241. Promise.all([
  1242. getUserInfo(userId).catch(() => null),
  1243. getUserUIState(userId).catch(() => null),
  1244. ]).then(([userInfoResult, uiStateResult]) => {
  1245. // 加载用户基本信息到 localStorage
  1246. if (userInfoResult?.success && userInfoResult.data) {
  1247. const userInfo = userInfoResult.data;
  1248. // Lyrria_user_name
  1249. if (userInfo.username) {
  1250. setUserName(userInfo.username);
  1251. }
  1252. // Lyrria_lumi_name
  1253. if (userInfo.bot_name) {
  1254. setStorage(STORAGE_KEYS.LUMI_NAME, userInfo.bot_name);
  1255. }
  1256. // Lyrria_user_level
  1257. if (typeof userInfo.user_level === 'number') {
  1258. syncUserLevel(userInfo.user_level);
  1259. }
  1260. // Lyrria_is_logged_in (根据 user_type 判断:registered 为已登录)
  1261. if (userInfo.user_type === 'registered') {
  1262. setStorage(STORAGE_KEYS.IS_LOGGED_IN, 'true');
  1263. } else {
  1264. setStorage(STORAGE_KEYS.IS_LOGGED_IN, 'false');
  1265. }
  1266. // Lyrria_current_background_image_id, Lyrria_current_background_image_url, Lyrria_current_background_image_opacity
  1267. if (userInfo.current_background_image_id) {
  1268. syncBackgroundImageToStorage(
  1269. userInfo.current_background_image_id,
  1270. userInfo.current_background_image_metadata
  1271. );
  1272. const bgUrl = getCurrentBackgroundImageUrl();
  1273. const bgId = getCurrentBackgroundImageId();
  1274. if (bgUrl) {
  1275. setBackgroundImageUrl(bgUrl);
  1276. }
  1277. if (bgId) {
  1278. setBackgroundImageId(bgId);
  1279. }
  1280. }
  1281. // 初始化进度条(基于 total_speech_duration_ms)
  1282. const totalDurationMs = userInfo.total_speech_duration_ms ?? 0;
  1283. if (totalDurationMs > 0) {
  1284. const PROGRESS_FULL_DURATION_MS = 30 * 1000; // 30000ms
  1285. totalSpeechDurationRef.current = Math.max(
  1286. totalDurationMs,
  1287. avatarCUnlockedRef.current ? AVATAR_C_UNLOCK_THRESHOLD_MS : 0
  1288. );
  1289. if (totalDurationMs >= AVATAR_C_UNLOCK_THRESHOLD_MS) {
  1290. unlockAvatarC();
  1291. }
  1292. const totalProgressPercent = (totalDurationMs / PROGRESS_FULL_DURATION_MS) * 100;
  1293. const initialProgress = totalProgressPercent % 100;
  1294. const initialLoopCount = Math.floor(totalProgressPercent / 100);
  1295. debugLog('[Progress] [初始化] 设置 shouldSkipProgressAnimation = true (Promise.all)', {
  1296. totalDurationMs,
  1297. totalProgressPercent,
  1298. initialProgress,
  1299. initialLoopCount,
  1300. });
  1301. // 在设置进度之前,先同步 prevProgressStateRef 和 totalProgressRef,避免动画计算错误
  1302. prevProgressStateRef.current = {
  1303. progress: initialProgress,
  1304. loopCount: initialLoopCount,
  1305. };
  1306. totalProgressRef.current = initialLoopCount * 100 + initialProgress;
  1307. shouldSkipProgressAnimationRef.current = true;
  1308. // 设置正确的圈数,而不是重置为 0
  1309. setProgress(initialProgress, initialLoopCount);
  1310. }
  1311. }
  1312. // 加载用户 UI 状态到 localStorage
  1313. if (uiStateResult?.success && uiStateResult.data) {
  1314. const state = uiStateResult.data;
  1315. // Lyrria_current_avatar_id
  1316. if (state.current_avatar_id) {
  1317. setCurrentAvatarId(state.current_avatar_id);
  1318. setStorage(STORAGE_KEYS.CURRENT_AVATAR_ID, state.current_avatar_id);
  1319. }
  1320. // Lyrria_current_page
  1321. if (state.current_page) {
  1322. setStorage(STORAGE_KEYS.CURRENT_PAGE, state.current_page);
  1323. }
  1324. // Lyrria_visited_routes (合并本地和数据库的路由,避免覆盖本地刚记录的路由)
  1325. const localVisited = getVisitedRoutes();
  1326. if (Array.isArray(state.visited_routes)) {
  1327. // 合并本地和数据库的路由,去重并保持顺序
  1328. const mergedRoutes = [...new Set([...localVisited, ...state.visited_routes])];
  1329. // 按照 ROUTE_ORDER 的顺序排序
  1330. const sortedRoutes = ROUTE_ORDER.filter(route => mergedRoutes.includes(route));
  1331. setStorage(STORAGE_KEYS.VISITED_ROUTES, JSON.stringify(sortedRoutes));
  1332. } else if (state.visited_routes === null || state.visited_routes === undefined) {
  1333. // 如果数据库中是 null 或 undefined,保留本地已有的路由
  1334. if (localVisited.length > 0) {
  1335. setStorage(STORAGE_KEYS.VISITED_ROUTES, JSON.stringify(localVisited));
  1336. } else {
  1337. setStorage(STORAGE_KEYS.VISITED_ROUTES, JSON.stringify([]));
  1338. }
  1339. }
  1340. // Lyrria_has_shown_tap_to_chat
  1341. if (state.has_shown_tap_to_chat) {
  1342. setStorage(STORAGE_KEYS.HAS_SHOWN_TAP_TO_CHAT, 'true');
  1343. if (isConnected) {
  1344. setShowTapToChat(false);
  1345. }
  1346. }
  1347. // Lyrria_has_shown_cancel_tooltip
  1348. if (state.has_shown_cancel_tooltip) {
  1349. setStorage(STORAGE_KEYS.HAS_SHOWN_CANCEL_TOOLTIP, 'true');
  1350. setShowCancelTooltip(false);
  1351. }
  1352. // Lyrria_has_shown_send_tooltip
  1353. if (state.has_shown_send_tooltip) {
  1354. setStorage(STORAGE_KEYS.HAS_SHOWN_SEND_TOOLTIP, 'true');
  1355. setShowSendTooltip(false);
  1356. }
  1357. // Lyrria_has_shown_progress_bar_tooltip
  1358. if (state.has_shown_progress_bar_tooltip) {
  1359. setStorage(STORAGE_KEYS.HAS_SHOWN_PROGRESS_BAR_TOOLTIP, 'true');
  1360. setHasShownProgressBarTooltip(true);
  1361. }
  1362. // Lyrria_avatar_c_unlocked
  1363. if (state.avatar_c_unlocked && !avatarCUnlockedRef.current) {
  1364. avatarCUnlockedRef.current = true;
  1365. setIsAvatarCUnlocked(true);
  1366. setStorage(STORAGE_KEYS.AVATAR_C_UNLOCKED, 'true');
  1367. }
  1368. // Lyrria_has_shared_avatar (无论 true/false,都从数据库同步)
  1369. setStorage(STORAGE_KEYS.HAS_SHARED_AVATAR, state.has_shared_avatar ? 'true' : 'false');
  1370. setHasSharedAvatarState(state.has_shared_avatar);
  1371. // Lyrria_has_shown_mission_stone_modal
  1372. if (state.has_shown_mission_stone_modal) {
  1373. setStorage(STORAGE_KEYS.HAS_SHOWN_MISSION_STONE_MODAL, 'true');
  1374. }
  1375. // Lyrria_has_shown_conversation_stone_modal
  1376. if (state.has_shown_conversation_stone_modal) {
  1377. setStorage(STORAGE_KEYS.HAS_SHOWN_CONVERSATION_STONE_MODAL, 'true');
  1378. }
  1379. // Lyrria_has_clicked_mission_stone
  1380. if (state.has_clicked_mission_stone) {
  1381. setStorage(STORAGE_KEYS.HAS_CLICKED_MISSION_STONE, 'true');
  1382. setHasClickedMissionStone(true);
  1383. }
  1384. // Lyrria_has_clicked_conversation_stone
  1385. if (state.has_clicked_conversation_stone) {
  1386. setStorage(STORAGE_KEYS.HAS_CLICKED_CONVERSATION_STONE, 'true');
  1387. setHasClickedConversationStone(true);
  1388. }
  1389. // 补偿同步:如果本地记录为 true 但后端为 false,尝试补偿同步
  1390. const localMissionShown = getStorage(STORAGE_KEYS.HAS_SHOWN_MISSION_STONE_MODAL) === 'true';
  1391. if (localMissionShown && !state.has_shown_mission_stone_modal) {
  1392. updateUserUIState(userId, {
  1393. has_shown_mission_stone_modal: true,
  1394. }).catch(() => {
  1395. // 静默处理
  1396. });
  1397. }
  1398. const localConversationShown =
  1399. getStorage(STORAGE_KEYS.HAS_SHOWN_CONVERSATION_STONE_MODAL) === 'true';
  1400. if (localConversationShown && !state.has_shown_conversation_stone_modal) {
  1401. updateUserUIState(userId, {
  1402. has_shown_conversation_stone_modal: true,
  1403. }).catch(() => {
  1404. // 静默处理
  1405. });
  1406. }
  1407. const localMissionClicked = getStorage(STORAGE_KEYS.HAS_CLICKED_MISSION_STONE) === 'true';
  1408. if (localMissionClicked && !state.has_clicked_mission_stone) {
  1409. updateUserUIState(userId, {
  1410. has_clicked_mission_stone: true,
  1411. }).catch(() => {
  1412. // 静默处理
  1413. });
  1414. }
  1415. const localConversationClicked = getStorage(STORAGE_KEYS.HAS_CLICKED_CONVERSATION_STONE) === 'true';
  1416. if (localConversationClicked && !state.has_clicked_conversation_stone) {
  1417. updateUserUIState(userId, {
  1418. has_clicked_conversation_stone: true,
  1419. }).catch(() => {
  1420. // 静默处理
  1421. });
  1422. }
  1423. }
  1424. }).catch(() => {
  1425. // 加载失败不影响主流程
  1426. console.warn('[ChatBotPage] 从数据库加载用户信息失败');
  1427. });
  1428. // 同步当前页面与已访问路由
  1429. updateUserUIState(userId, {
  1430. current_page: 'chatbot',
  1431. visited_routes: visited,
  1432. }).catch(() => {
  1433. // 同步失败不影响主流程
  1434. });
  1435. }
  1436. const init = async () => {
  1437. try {
  1438. // 获取用户信息并初始化进度条(已在上面 Promise.all 中处理,这里保留作为兜底)
  1439. const user_id = getUserId();
  1440. if (user_id) {
  1441. try {
  1442. const userInfo = await getUserInfo(user_id);
  1443. if (userInfo.success && userInfo.data) {
  1444. // 同步用户名到 localStorage
  1445. if (userInfo.data.username) {
  1446. setUserName(userInfo.data.username);
  1447. }
  1448. // 同步机器人名字到 localStorage
  1449. if (userInfo.data.bot_name) {
  1450. setStorage(STORAGE_KEYS.LUMI_NAME, userInfo.data.bot_name);
  1451. }
  1452. // 同步用户等级
  1453. const totalDurationMs = userInfo.data.total_speech_duration_ms ?? 0;
  1454. if (typeof userInfo.data.user_level === 'number') {
  1455. syncUserLevel(userInfo.data.user_level);
  1456. }
  1457. // 同步背景图片
  1458. if (userInfo.data.current_background_image_id) {
  1459. syncBackgroundImageToStorage(
  1460. userInfo.data.current_background_image_id,
  1461. userInfo.data.current_background_image_metadata
  1462. );
  1463. const bgUrl = getCurrentBackgroundImageUrl();
  1464. const bgId = getCurrentBackgroundImageId();
  1465. if (bgUrl) {
  1466. setBackgroundImageUrl(bgUrl);
  1467. }
  1468. if (bgId) {
  1469. setBackgroundImageId(bgId);
  1470. }
  1471. }
  1472. if (totalDurationMs > 0) {
  1473. // 根据总说话时长计算初始进度(30秒=100%)
  1474. const PROGRESS_FULL_DURATION_MS = 30 * 1000; // 30000ms
  1475. totalSpeechDurationRef.current = Math.max(
  1476. totalDurationMs,
  1477. avatarCUnlockedRef.current ? AVATAR_C_UNLOCK_THRESHOLD_MS : 0
  1478. );
  1479. if (totalDurationMs >= AVATAR_C_UNLOCK_THRESHOLD_MS) {
  1480. unlockAvatarC();
  1481. }
  1482. // 计算总进度百分比和圈数
  1483. const totalProgressPercent = (totalDurationMs / PROGRESS_FULL_DURATION_MS) * 100;
  1484. const initialProgress = totalProgressPercent % 100;
  1485. const initialLoopCount = Math.floor(totalProgressPercent / 100);
  1486. debugLog('[Progress] [初始化] 设置 shouldSkipProgressAnimation = true (init)', {
  1487. totalDurationMs,
  1488. totalProgressPercent,
  1489. initialProgress,
  1490. initialLoopCount,
  1491. });
  1492. // 在设置进度之前,先同步 prevProgressStateRef 和 totalProgressRef,避免动画计算错误
  1493. prevProgressStateRef.current = {
  1494. progress: initialProgress,
  1495. loopCount: initialLoopCount,
  1496. };
  1497. totalProgressRef.current = initialLoopCount * 100 + initialProgress;
  1498. shouldSkipProgressAnimationRef.current = true;
  1499. // 设置正确的圈数,而不是重置为 0
  1500. setProgress(initialProgress, initialLoopCount);
  1501. }
  1502. }
  1503. } catch (error) {
  1504. // 获取用户信息失败不影响主流程,静默处理
  1505. console.warn('获取用户信息失败:', error);
  1506. }
  1507. }
  1508. // 初始化录音器
  1509. const recorder = new AudioRecorder();
  1510. await recorder.initialize();
  1511. recorderRef.current = recorder;
  1512. // 初始化播放器
  1513. const player = new AudioPlayer();
  1514. await player.initialize();
  1515. // 音频即将结束前的回调:提前结束情绪/说话 GIF,避免尾部静音导致动画拖尾
  1516. player.onBeforeEnd(() => {
  1517. const snapshot = useAppStore.getState();
  1518. debugLog('[AudioPlayer] onBeforeEnd: audio about to finish, early stop GIF', {
  1519. currentState: snapshot.currentState,
  1520. currentRequestId: snapshot.currentRequestId
  1521. ? snapshot.currentRequestId.substring(0, 8)
  1522. : null,
  1523. });
  1524. // 本次对话即将结束,提前清理情绪状态和 GIF 切换定时器
  1525. pendingEmotionRef.current = null;
  1526. if (emotionGifTimerRef.current) {
  1527. clearTimeout(emotionGifTimerRef.current);
  1528. emotionGifTimerRef.current = null;
  1529. }
  1530. // 提前切回默认头像 GIF,避免 talking/情绪 GIF 多播 1-2 秒
  1531. showDefaultGif();
  1532. });
  1533. // 音频开始播放回调:统一驱动情绪 GIF + talking GIF
  1534. player.onStart(() => {
  1535. const appStateSnapshot = useAppStore.getState();
  1536. const now = Date.now();
  1537. debugLog('[AudioPlayer] 音频开始播放,准备切换情绪/说话 GIF', {
  1538. currentState: appStateSnapshot.currentState,
  1539. currentRequestId: appStateSnapshot.currentRequestId
  1540. ? appStateSnapshot.currentRequestId.substring(0, 8)
  1541. : null,
  1542. currentEmotion: appStateSnapshot.currentEmotion,
  1543. clientNow: now,
  1544. });
  1545. // 优先使用缓存的情绪;如果没有,则使用 store 中当前情绪
  1546. const cachedEmotion = pendingEmotionRef.current;
  1547. const latestEmotion = cachedEmotion || appStateSnapshot.currentEmotion;
  1548. pendingEmotionRef.current = null;
  1549. const emotionCategory = getEmotionCategory(latestEmotion);
  1550. debugLog('[AudioPlayer] onStart emotion category resolved', {
  1551. cachedEmotion,
  1552. latestEmotion,
  1553. emotionCategory,
  1554. });
  1555. // 任何新的播放开始都应清理旧的情绪定时器,避免串台
  1556. if (emotionGifTimerRef.current) {
  1557. clearTimeout(emotionGifTimerRef.current);
  1558. emotionGifTimerRef.current = null;
  1559. debugLog('[AudioPlayer] onStart: cleared previous emotionGifTimer');
  1560. }
  1561. if (emotionCategory === 'positive') {
  1562. // 正向情绪:播放一次正向情绪 GIF,然后自动切回 talking
  1563. showPositiveGif();
  1564. debugLog('[AudioPlayer] onStart: showPositiveGif');
  1565. const currentAvatarId = getStorage(STORAGE_KEYS.CURRENT_AVATAR_ID);
  1566. const duration = getEmotionGifDuration(currentAvatarId, emotionCategory);
  1567. if (duration > 0) {
  1568. emotionGifTimerRef.current = window.setTimeout(() => {
  1569. debugLog('[AudioPlayer] emotionGifTimer fired: positive -> talking', {
  1570. duration,
  1571. avatarId: currentAvatarId,
  1572. });
  1573. showTalkingGif();
  1574. emotionGifTimerRef.current = null;
  1575. }, duration);
  1576. } else {
  1577. // 理论上不会走到这里,兜底切 talking
  1578. debugLog('[AudioPlayer] onStart: positive emotion duration unknown, fallback talking');
  1579. showTalkingGif();
  1580. }
  1581. } else if (emotionCategory === 'negative') {
  1582. // 负向情绪:播放一次负向情绪 GIF,然后自动切回 talking
  1583. showNegativeGif();
  1584. debugLog('[AudioPlayer] onStart: showNegativeGif');
  1585. const currentAvatarId = getStorage(STORAGE_KEYS.CURRENT_AVATAR_ID);
  1586. const duration = getEmotionGifDuration(currentAvatarId, emotionCategory);
  1587. if (duration > 0) {
  1588. emotionGifTimerRef.current = window.setTimeout(() => {
  1589. debugLog('[AudioPlayer] emotionGifTimer fired: negative -> talking', {
  1590. duration,
  1591. avatarId: currentAvatarId,
  1592. });
  1593. showTalkingGif();
  1594. emotionGifTimerRef.current = null;
  1595. }, duration);
  1596. } else {
  1597. debugLog('[AudioPlayer] onStart: negative emotion duration unknown, fallback talking');
  1598. showTalkingGif();
  1599. }
  1600. } else {
  1601. // 中性或未知情绪:直接进入 talking 状态
  1602. debugLog('[AudioPlayer] onStart: neutral/unknown emotion, showTalkingGif');
  1603. showTalkingGif();
  1604. }
  1605. });
  1606. // 音频播放结束回调:强制回归 default,本次对话收尾
  1607. player.onEnd(() => {
  1608. const snapshot = useAppStore.getState();
  1609. const requestId = snapshot.currentRequestId;
  1610. debugLog('[AudioPlayer] onEnd: audio playback finished', {
  1611. currentState: snapshot.currentState,
  1612. currentRequestId: requestId ? requestId.substring(0, 8) : null,
  1613. });
  1614. if (requestId) {
  1615. performanceLogger.recordPlaybackEnd(requestId);
  1616. }
  1617. // 本次对话已结束,清理待处理情绪
  1618. pendingEmotionRef.current = null;
  1619. // 进度条已基于用户说话时长更新,无需在播放完成后再次更新
  1620. // 清理情绪 GIF 切换定时器
  1621. if (emotionGifTimerRef.current) {
  1622. clearTimeout(emotionGifTimerRef.current);
  1623. emotionGifTimerRef.current = null;
  1624. debugLog('[AudioPlayer] onEnd: cleared emotionGifTimer and reset to default GIF');
  1625. }
  1626. // 恢复默认头像 GIF(无论当前处于何种 GIF 状态)
  1627. showDefaultGif();
  1628. setState('idle');
  1629. reset();
  1630. });
  1631. playerRef.current = player;
  1632. // 初始化WebSocket前确保会话已就绪(支持用户直接刷新/直达聊天页)
  1633. // 🔧 如果 URL 中有 OAuth 回调参数,说明正在处理登录回调,不调用 ensureSession(避免创建新用户)
  1634. const oauthFromUrl = searchParams.get('oauth');
  1635. const userIdFromUrl = searchParams.get('user_id');
  1636. if (!oauthFromUrl || !userIdFromUrl) {
  1637. // 只有在非 OAuth 回调时才调用 ensureSession
  1638. try {
  1639. await ensureSession();
  1640. } catch (error) {
  1641. console.error('[ChatBotPage] ensureSession 失败,无法初始化 WebSocket:', error);
  1642. clearUserSessionAndRedirectToBegin();
  1643. return;
  1644. }
  1645. } else {
  1646. console.log(`[ChatBotPage] 检测到 OAuth 回调,跳过 ensureSession - oauth=${oauthFromUrl}, user_id=${userIdFromUrl}`);
  1647. }
  1648. // 初始化WebSocket(添加 user_id + token 查询参数,单活)
  1649. const ws = new WebSocketManager();
  1650. const token = getUserToken();
  1651. const params = new URLSearchParams();
  1652. if (user_id) {
  1653. params.append('user_id', user_id);
  1654. }
  1655. if (token) {
  1656. params.append('token', token);
  1657. }
  1658. ws.setAuth(
  1659. { userId: user_id || undefined, token: token || undefined },
  1660. async () => {
  1661. // 服务端明确标记会话失效时(如在其他设备登录),直接清理本地状态并跳转到 /begin
  1662. clearUserSessionAndRedirectToBegin();
  1663. return false;
  1664. }
  1665. );
  1666. const wsUrl = params.toString() ? `${WS_URL}?${params.toString()}` : WS_URL;
  1667. ws.connect(wsUrl, (connected) => {
  1668. // 如果组件已卸载,不执行任何操作
  1669. if (!isMountedRef.current) {
  1670. return;
  1671. }
  1672. const appState = useAppStore.getState();
  1673. const wasConnected = appState.isConnected;
  1674. setConnected(connected);
  1675. if (connected) {
  1676. // 记录WebSocket连接建立时间
  1677. performanceLogger.recordWebSocketConnected();
  1678. // 如果这是首次连接成功,处理 TapToChat 提示
  1679. if (!connectionLostRef.current) {
  1680. const hasShown = getStorage(STORAGE_KEYS.HAS_SHOWN_TAP_TO_CHAT);
  1681. if (!hasShown && showTapToChat) {
  1682. // 第一次连接成功,保存标记
  1683. setStorage(STORAGE_KEYS.HAS_SHOWN_TAP_TO_CHAT, 'true');
  1684. // 同步到后端 UI 状态(如果已有 user_id)
  1685. const userId = getUserId();
  1686. if (userId) {
  1687. updateUserUIState(userId, {
  1688. has_shown_tap_to_chat: true,
  1689. }).catch(() => {
  1690. // 同步失败不影响前端提示展示
  1691. });
  1692. }
  1693. } else if (hasShown) {
  1694. // 如果已经标记为已显示(可能是从后端同步的),现在 WebSocket 已连接,可以安全隐藏
  1695. setShowTapToChat(false);
  1696. }
  1697. }
  1698. if (connectionLostRef.current) {
  1699. antMessage.success('语音服务已恢复,可以继续对话');
  1700. connectionLostRef.current = false;
  1701. recorderRef.current?.stop();
  1702. resetFrequencyVisualization();
  1703. playerRef.current?.stop();
  1704. // 清理解码中的情绪状态与 GIF 切换定时器
  1705. pendingEmotionRef.current = null;
  1706. if (emotionGifTimerRef.current) {
  1707. clearTimeout(emotionGifTimerRef.current);
  1708. emotionGifTimerRef.current = null;
  1709. }
  1710. // 恢复默认头像 GIF
  1711. showDefaultGif();
  1712. reset();
  1713. setError(null);
  1714. }
  1715. return;
  1716. }
  1717. if (!wasConnected) {
  1718. // 初次连接失败,静默等待自动重连
  1719. return;
  1720. }
  1721. connectionLostRef.current = true;
  1722. if (appState.currentRequestId) {
  1723. performanceLogger.clearRequest(appState.currentRequestId, 'websocket_disconnected');
  1724. }
  1725. recorderRef.current?.stop();
  1726. resetFrequencyVisualization();
  1727. playerRef.current?.stop();
  1728. // 清理解码中的情绪状态与 GIF 切换定时器
  1729. pendingEmotionRef.current = null;
  1730. if (emotionGifTimerRef.current) {
  1731. clearTimeout(emotionGifTimerRef.current);
  1732. emotionGifTimerRef.current = null;
  1733. }
  1734. // 恢复默认头像 GIF
  1735. showDefaultGif();
  1736. antMessage.error('语音服务连接断开,请稍后重试');
  1737. setError('语音服务连接断开,请稍后重试');
  1738. });
  1739. ws.onMessage('app', handleMessage);
  1740. wsRef.current = ws;
  1741. } catch (error) {
  1742. antMessage.error('初始化失败,请检查麦克风权限');
  1743. setError('初始化失败');
  1744. }
  1745. };
  1746. init();
  1747. return () => {
  1748. // 标记组件已卸载,防止 WebSocket 回调显示错误消息
  1749. isMountedRef.current = false;
  1750. recorderRef.current?.release();
  1751. playerRef.current?.release();
  1752. wsRef.current?.disconnect();
  1753. resetFrequencyVisualization();
  1754. if (sendingTimeoutRef.current) {
  1755. clearTimeout(sendingTimeoutRef.current);
  1756. }
  1757. if (animationFrameRef.current) {
  1758. cancelAnimationFrame(animationFrameRef.current);
  1759. }
  1760. if (progressBarTooltipTimerRef.current) {
  1761. clearTimeout(progressBarTooltipTimerRef.current);
  1762. }
  1763. if (emotionGifTimerRef.current) {
  1764. clearTimeout(emotionGifTimerRef.current);
  1765. }
  1766. // 组件卸载时不再保留任何待处理情绪,避免内存中残留过期状态
  1767. pendingEmotionRef.current = null;
  1768. };
  1769. }, [resetFrequencyVisualization]);
  1770. // 处理WebSocket消息
  1771. const handleMessage = (message: Message) => {
  1772. const requestId = message.requestId || currentRequestId;
  1773. if (!requestId) {
  1774. console.warn('[ChatBotPage] 收到缺少 requestId 的消息,已忽略', message.type);
  1775. return;
  1776. }
  1777. const activeRequestId = activeRequestIdRef.current;
  1778. const isCancelledRequest = cancelledRequestIdsRef.current.has(requestId);
  1779. // 🔥 首句消息特殊处理(requestId 以 "greeting_" 开头)
  1780. const isGreetingMessage = requestId.startsWith('greeting_');
  1781. // 记录首句 requestId,便于后续在开始录音时发送 cancel
  1782. if (isGreetingMessage && !greetingRequestIdRef.current) {
  1783. greetingRequestIdRef.current = requestId;
  1784. }
  1785. // 如果用户已经开始录音且选择“以用户为准”,则直接丢弃所有首句相关消息
  1786. if (isGreetingMessage && greetingSuppressedRef.current) {
  1787. debugLog(`[首句] [${requestId.substring(0, 8)}] 已被用户录音打断,忽略首句消息: ${message.type}`);
  1788. return;
  1789. }
  1790. if (isCancelledRequest && !isGreetingMessage) {
  1791. if (message.type === 'audio_response' && message.isLast) {
  1792. cancelledRequestIdsRef.current.delete(requestId);
  1793. }
  1794. debugLog(`[${message.type}] [${requestId.substring(0, 8)}] 已取消的请求,忽略响应`);
  1795. return;
  1796. }
  1797. switch (message.type) {
  1798. case 'text_result':
  1799. // 🔥 首句消息:直接处理,不检查 activeRequestId
  1800. if (isGreetingMessage) {
  1801. // 首句文本:添加到消息列表(作为 assistant 消息)
  1802. if (message.isFinal) {
  1803. // 这里可以添加消息到聊天历史(如果需要显示在界面上)
  1804. debugLog(`[首句文本] [${requestId.substring(0, 8)}] ${message.text}`);
  1805. // 设置识别文本,让前端显示
  1806. setRecognizedText(message.text);
  1807. }
  1808. break;
  1809. }
  1810. // 如果当前状态是 recording,且 requestId 不匹配当前请求,说明这是旧请求的返回,直接丢弃
  1811. // 如果 activeRequestId 为 null,说明是新请求的开始,允许处理
  1812. if (activeRequestId !== null && requestId !== activeRequestId) {
  1813. debugLog(`[文本结果] [${requestId.substring(0, 8)}] 请求ID不匹配,丢弃旧请求的文本结果`);
  1814. break;
  1815. }
  1816. if (message.isFinal) {
  1817. performanceLogger.recordFinalText(requestId, message.text, message.timestamp);
  1818. } else if (!performanceLogger.hasFirstText(requestId)) {
  1819. performanceLogger.recordFirstText(requestId, message.text, message.timestamp);
  1820. }
  1821. setRecognizedText(message.text);
  1822. break;
  1823. case 'user_level':
  1824. if (typeof message.level === 'number') {
  1825. syncUserLevel(message.level);
  1826. }
  1827. // 🔥 使用后端返回的 totalDurationMs 同步进度条,确保与数据库一致
  1828. if (typeof message.totalDurationMs === 'number' && message.totalDurationMs > 0) {
  1829. const PROGRESS_FULL_DURATION_MS = 30 * 1000; // 30000ms
  1830. // 满足解锁阈值时实时解锁,避免必须刷新页面
  1831. if (message.totalDurationMs >= AVATAR_C_UNLOCK_THRESHOLD_MS && !avatarCUnlockedRef.current) {
  1832. unlockAvatarC();
  1833. }
  1834. // 更新本地累加器,确保与数据库一致
  1835. totalSpeechDurationRef.current = Math.max(
  1836. message.totalDurationMs,
  1837. avatarCUnlockedRef.current ? AVATAR_C_UNLOCK_THRESHOLD_MS : 0
  1838. );
  1839. // 根据总时长计算进度条位置(只显示非整数圈的进度)
  1840. const totalProgressPercent = (message.totalDurationMs / PROGRESS_FULL_DURATION_MS) * 100;
  1841. const progress = totalProgressPercent % 100;
  1842. // 🔍 检查当前状态,如果用户刚刚更新了进度,不要覆盖用户的更新
  1843. const currentState = useAppStore.getState();
  1844. const currentTotal = currentState.progressLoopCount * 100 + currentState.conversationProgress;
  1845. const newTotal = Math.floor(totalProgressPercent / 100) * 100 + progress;
  1846. debugLog('[Progress] [user_level] 收到后端同步请求', {
  1847. totalDurationMs: message.totalDurationMs,
  1848. progress,
  1849. currentTotal,
  1850. newTotal,
  1851. requestId: requestId?.substring(0, 8),
  1852. shouldSync: Math.abs(currentTotal - newTotal) > 0.1, // 只有差异较大时才同步
  1853. });
  1854. // 只有在差异较大时才同步(避免覆盖用户刚刚的更新)
  1855. if (Math.abs(currentTotal - newTotal) > 0.1) {
  1856. // 计算应该保持的圈数(基于总时长)
  1857. const targetLoopCount = Math.floor(totalProgressPercent / 100);
  1858. // 只在初始化时跳过动画(如果当前进度接近0)
  1859. const isInitialSync = currentTotal < 1;
  1860. if (isInitialSync) {
  1861. debugLog('[Progress] [user_level] 初始化同步,跳过动画但同步进度');
  1862. shouldSkipProgressAnimationRef.current = true;
  1863. }
  1864. // 无论是否初始化,都同步进度值,动画是否播放由 shouldSkipProgressAnimationRef 控制
  1865. debugLog('[Progress] [user_level] 同步进度,设置进度值:', {
  1866. progress,
  1867. targetLoopCount,
  1868. });
  1869. // 保持当前的圈数,不重置为0
  1870. setProgress(progress, targetLoopCount);
  1871. } else {
  1872. debugLog('[Progress] [user_level] 差异太小,跳过同步');
  1873. }
  1874. }
  1875. break;
  1876. case 'emotion':
  1877. // 🔥 首句消息:直接处理,不检查 activeRequestId
  1878. if (isGreetingMessage) {
  1879. performanceLogger.recordEmotion(requestId, message.emotion, message.timestamp);
  1880. setEmotion(message.emotion);
  1881. // 🔥 仅缓存情绪,不立即切换 GIF,等待首句音频真正开始播放时再驱动动画
  1882. pendingEmotionRef.current = message.emotion;
  1883. break;
  1884. }
  1885. // 如果当前状态是 recording,且 requestId 不匹配当前请求,说明这是旧请求的返回,直接丢弃
  1886. // 如果 activeRequestId 为 null,说明是新请求的开始,允许处理
  1887. if (activeRequestId !== null && requestId !== activeRequestId) {
  1888. debugLog(`[情绪] [${requestId.substring(0, 8)}] 请求ID不匹配,丢弃旧请求的情绪`);
  1889. break;
  1890. }
  1891. performanceLogger.recordEmotion(requestId, message.emotion, message.timestamp);
  1892. setEmotion(message.emotion);
  1893. // 🔥 普通情绪消息同样只缓存,真正的情绪动画在音频开始播放时统一处理
  1894. pendingEmotionRef.current = message.emotion;
  1895. break;
  1896. case 'audio_response':
  1897. // 🔥 首句消息:直接处理,不检查状态和 activeRequestId
  1898. if (isGreetingMessage) {
  1899. // 首句音频:自动播放
  1900. if (currentState !== 'playing') {
  1901. const now = Date.now();
  1902. debugLog(`[音频响应][首句] [${requestId.substring(0, 8)}] 首次音频块,进入 playing 状态`, {
  1903. messageTimestamp: message.timestamp,
  1904. clientNow: now,
  1905. delayMs: typeof message.timestamp === 'number' ? now - message.timestamp : null,
  1906. });
  1907. performanceLogger.recordFirstAudio(requestId, message.timestamp);
  1908. performanceLogger.recordPlaybackStart(requestId);
  1909. setState('playing');
  1910. }
  1911. // 标记当前处于首句播放阶段,便于后续开始录音时精确打断
  1912. isGreetingActiveRef.current = true;
  1913. if (message.data && playerRef.current) {
  1914. // 将 base64 字符串解码为 Uint8Array
  1915. const audioData = atob(message.data);
  1916. const audioBytes = new Uint8Array(audioData.length);
  1917. for (let i = 0; i < audioData.length; i++) {
  1918. audioBytes[i] = audioData.charCodeAt(i);
  1919. }
  1920. playerRef.current.addChunk(audioBytes, message.sampleRate || 24000);
  1921. }
  1922. if (message.isLast) {
  1923. performanceLogger.recordLastAudio(requestId);
  1924. playerRef.current?.markStreamEnd();
  1925. // 首句自然播放结束
  1926. isGreetingActiveRef.current = false;
  1927. greetingRequestIdRef.current = null;
  1928. }
  1929. break;
  1930. }
  1931. // 如果当前状态是 recording,说明用户已经点击了录音按钮,忽略后续的音频响应
  1932. if (currentState === 'recording') {
  1933. debugLog(`[音频响应] [${requestId.substring(0, 8)}] 用户已开始录音,忽略音频响应`);
  1934. break;
  1935. }
  1936. // 如果 currentRequestId 不为 null,且 requestId 不匹配当前请求,说明这是旧请求的返回,直接丢弃
  1937. // 如果 activeRequestId 为 null,说明是新请求的开始,允许处理
  1938. if (activeRequestId !== null && requestId !== activeRequestId) {
  1939. debugLog(`[音频响应] [${requestId.substring(0, 8)}] 请求ID不匹配,丢弃旧请求的音频响应`, {
  1940. activeRequestId: activeRequestId ? activeRequestId.substring(0, 8) : null,
  1941. messageIsLast: message.isLast,
  1942. });
  1943. break;
  1944. }
  1945. // 清除发送超时
  1946. if (sendingTimeoutRef.current) {
  1947. clearTimeout(sendingTimeoutRef.current);
  1948. sendingTimeoutRef.current = null;
  1949. }
  1950. if (currentState !== 'playing') {
  1951. const now = Date.now();
  1952. debugLog(`[音频响应] [${requestId.substring(0, 8)}] 首次音频块,进入 playing 状态`, {
  1953. messageTimestamp: message.timestamp,
  1954. clientNow: now,
  1955. delayMs: typeof message.timestamp === 'number' ? now - message.timestamp : null,
  1956. });
  1957. performanceLogger.recordFirstAudio(requestId, message.timestamp);
  1958. performanceLogger.recordPlaybackStart(requestId);
  1959. setState('playing');
  1960. }
  1961. if (message.data) {
  1962. const audioData = atob(message.data);
  1963. const audioBytes = new Uint8Array(audioData.length);
  1964. for (let i = 0; i < audioData.length; i++) {
  1965. audioBytes[i] = audioData.charCodeAt(i);
  1966. }
  1967. debugLog(`[音频响应] [${requestId.substring(0, 8)}] 收到音频数据块`, {
  1968. bytes: audioBytes.length,
  1969. sampleRate: message.sampleRate || 24000,
  1970. isLast: message.isLast,
  1971. });
  1972. playerRef.current?.addChunk(audioBytes, message.sampleRate || 24000);
  1973. }
  1974. if (message.isLast) {
  1975. debugLog(`[音频响应] [${requestId.substring(0, 8)}] 收到 isLast=true,标记音频流结束`);
  1976. performanceLogger.recordLastAudio(requestId);
  1977. playerRef.current?.markStreamEnd();
  1978. // 进度已在发送时增加,这里不再重复增加
  1979. }
  1980. break;
  1981. case 'energy_stone_spawn':
  1982. handleEnergyStoneSpawn(message);
  1983. break;
  1984. case 'error':
  1985. console.error(`[错误] [${requestId?.substring(0, 8) || ''}]`, message.message, message.code);
  1986. // 静默处理后端错误提示,避免打扰用户
  1987. debugLog('[ServiceError]', message.message, message.code);
  1988. setError(message.message);
  1989. if (message.code === 'SESSION_INVALIDATED') {
  1990. // 会话在其他设备被顶掉:清理会话并统一跳转到 /begin
  1991. wsRef.current?.disconnect();
  1992. antMessage.error('会话已在其他设备登录,请重新进入');
  1993. clearUserSessionAndRedirectToBegin();
  1994. return;
  1995. }
  1996. // 清理情绪 GIF 切换定时器
  1997. if (emotionGifTimerRef.current) {
  1998. clearTimeout(emotionGifTimerRef.current);
  1999. emotionGifTimerRef.current = null;
  2000. }
  2001. // 恢复默认头像 GIF
  2002. showDefaultGif();
  2003. performanceLogger.clearRequest(requestId, `${message.code}: ${message.message}`);
  2004. break;
  2005. case 'pong':
  2006. break;
  2007. default:
  2008. console.warn(`[未知消息] [${requestId?.substring(0, 8) || ''}]`, message.type);
  2009. break;
  2010. }
  2011. };
  2012. // 开始录音
  2013. const handleStartRecord = async () => {
  2014. // 如果正在录音,忽略
  2015. if (currentState === 'recording') {
  2016. return;
  2017. }
  2018. // 🔥 改进:允许在连接建立过程中开始录音
  2019. // 1. 如果 WebSocket 不存在,说明还未初始化,提示等待
  2020. // 2. 如果 WebSocket 存在,检查是否正在连接中或已就绪
  2021. // 3. 如果正在连接中(CONNECTING)或已就绪(OPEN),允许开始录音,消息会被缓冲
  2022. // 4. 这样用户无感知,业务也能正常运行
  2023. if (!wsRef.current) {
  2024. antMessage.warning('语音服务初始化中,请稍后重试');
  2025. return;
  2026. }
  2027. // 检查 WebSocket 状态:如果正在连接中或已就绪,允许开始录音
  2028. const isConnecting = wsRef.current.isConnecting();
  2029. const isReady = wsRef.current.isReady();
  2030. // 如果既不在连接中,也不已就绪,且 isConnected 为 false,说明连接失败
  2031. if (!isConnecting && !isReady && !isConnected) {
  2032. // 静默提示:语音服务重连中
  2033. debugLog('[SendGuard] 语音服务正在重连');
  2034. return;
  2035. }
  2036. // 如果正在连接中或已就绪,允许开始录音(消息会被缓冲)
  2037. // 保存旧请求ID(用于取消和过滤旧消息)
  2038. const oldRequestId = currentRequestId;
  2039. const wasPlaying = currentState === 'playing' || currentState === 'sending';
  2040. // 如果正在播放,先停止播放并重置状态
  2041. if (wasPlaying) {
  2042. // 停止音频播放(包括可能正在播放的首句)
  2043. playerRef.current?.stop();
  2044. // 清理情绪 GIF 切换定时器
  2045. if (emotionGifTimerRef.current) {
  2046. clearTimeout(emotionGifTimerRef.current);
  2047. emotionGifTimerRef.current = null;
  2048. }
  2049. // 立即恢复默认头像 GIF
  2050. showDefaultGif();
  2051. // 取消当前的请求(如果有),丢弃上一次请求的返回
  2052. if (oldRequestId) {
  2053. wsRef.current?.sendCancel(oldRequestId);
  2054. cancelledRequestIdsRef.current.add(oldRequestId);
  2055. performanceLogger.clearRequest(oldRequestId, '用户中断播放开始新录音');
  2056. }
  2057. // 清理旧请求的状态(丢弃上一次请求的返回)
  2058. setRecognizedText('');
  2059. setEmotion('neutral');
  2060. // 清理发送超时
  2061. if (sendingTimeoutRef.current) {
  2062. clearTimeout(sendingTimeoutRef.current);
  2063. sendingTimeoutRef.current = null;
  2064. }
  2065. }
  2066. // 其他状态(idle/error/sending)都允许开始录音
  2067. // 一旦用户主动开始录音,则以用户为准:后续所有首句 greeting 消息全部丢弃
  2068. greetingSuppressedRef.current = true;
  2069. // 如果此时已经拿到首句的 requestId,则主动向后端发送 cancel,节省资源
  2070. if (greetingRequestIdRef.current) {
  2071. const greetingId = greetingRequestIdRef.current;
  2072. wsRef.current?.sendCancel(greetingId);
  2073. cancelledRequestIdsRef.current.add(greetingId);
  2074. debugLog(`[首句] [${greetingId.substring(0, 8)}] 用户开始录音,发送 cancel 终止首句`);
  2075. }
  2076. // 首次点击录音按钮,隐藏 TapToChat 提示并保存标记
  2077. if (showTapToChat) {
  2078. setShowTapToChat(false);
  2079. // 确保标记已保存(防止 WebSocket 连接较慢时未保存)
  2080. const hasShown = getStorage(STORAGE_KEYS.HAS_SHOWN_TAP_TO_CHAT);
  2081. if (!hasShown) {
  2082. setStorage(STORAGE_KEYS.HAS_SHOWN_TAP_TO_CHAT, 'true');
  2083. // 同步到后端 UI 状态(如果已有 user_id)
  2084. const userId = getUserId();
  2085. if (userId) {
  2086. updateUserUIState(userId, {
  2087. has_shown_tap_to_chat: true,
  2088. }).catch(() => {
  2089. // 同步失败不影响主流程
  2090. });
  2091. }
  2092. }
  2093. }
  2094. // 点击录音按钮时,隐藏进度条提示
  2095. dismissProgressBarTooltip();
  2096. // 🔥 清理播放器状态,确保上一次对话的残留状态被重置
  2097. playerRef.current?.stop();
  2098. // 生成新的请求ID并立即设置,确保后续消息能正确匹配
  2099. const requestId = uuidv4();
  2100. performanceLogger.startRequest(requestId);
  2101. updateRequestId(requestId);
  2102. setState('recording');
  2103. chunkIndexRef.current = 0;
  2104. setRecognizedText('');
  2105. // 准备移动端音频(在设置状态之后,避免阻塞状态更新)
  2106. // 🔥 改进:静默准备音频环境,不显示提示,用户无感知
  2107. if (isMobileDevice() && !mobileAudioPreparedRef.current) {
  2108. // 异步准备,不阻塞录音开始
  2109. prepareMobileAudio()
  2110. .then(() => {
  2111. requestVolumeControl();
  2112. mobileAudioPreparedRef.current = true;
  2113. // 移除提示,让用户无感知,业务功能正常(prepareMobileAudio 和 requestVolumeControl 仍会执行)
  2114. })
  2115. .catch(() => {
  2116. // 准备移动端音频失败,静默处理
  2117. });
  2118. }
  2119. timingRef.current = {
  2120. recordStart: Date.now(),
  2121. recordEnd: 0,
  2122. firstAudioReceived: 0,
  2123. emotionReceived: 0,
  2124. };
  2125. // 立即启动录音,确保第一次点击就能开始
  2126. try {
  2127. await recorderRef.current?.start((pcmData) => {
  2128. // 检查当前状态,如果已经不是recording,说明用户可能又点击了,忽略
  2129. const currentStateCheck = useAppStore.getState().currentState;
  2130. if (currentStateCheck !== 'recording') {
  2131. return;
  2132. }
  2133. if (chunkIndexRef.current === 0) {
  2134. performanceLogger.recordFirstChunkSent(requestId);
  2135. }
  2136. const uint8Array = new Uint8Array(pcmData.buffer);
  2137. const base64 = btoa(String.fromCharCode(...Array.from(uint8Array)));
  2138. wsRef.current?.sendAudioChunk(requestId, base64, chunkIndexRef.current);
  2139. chunkIndexRef.current++;
  2140. }, pushFrequencyFrame);
  2141. // 录音启动成功,开始计时
  2142. startRecordingTimer();
  2143. } catch (error) {
  2144. console.error(`[录音] [${requestId.substring(0, 8)}] 启动失败`, error);
  2145. antMessage.error('麦克风启动失败,请检查权限或重试');
  2146. performanceLogger.clearRequest(requestId, 'recorder_start_failed');
  2147. resetFrequencyVisualization();
  2148. // 清理解码中的情绪状态与 GIF 切换定时器
  2149. pendingEmotionRef.current = null;
  2150. if (emotionGifTimerRef.current) {
  2151. clearTimeout(emotionGifTimerRef.current);
  2152. emotionGifTimerRef.current = null;
  2153. }
  2154. // 恢复默认头像 GIF
  2155. showDefaultGif();
  2156. setState('idle');
  2157. reset();
  2158. return;
  2159. }
  2160. };
  2161. // 发送录音
  2162. const handleSend = () => {
  2163. if (currentState !== 'recording' || !currentRequestId) {
  2164. return;
  2165. }
  2166. stopRecordingTimer();
  2167. // 🔥 改进:允许在连接建立过程中发送录音
  2168. // 1. 如果 WebSocket 不存在,说明还未初始化,提示错误
  2169. // 2. 如果 WebSocket 存在,检查是否正在连接中或已就绪
  2170. // 3. 如果正在连接中(CONNECTING)或已就绪(OPEN),允许发送,消息会被缓冲
  2171. // 4. 这样用户无感知,业务也能正常运行
  2172. if (!wsRef.current) {
  2173. // 静默处理:语音服务初始化中
  2174. debugLog('[SendGuard] 语音服务初始化中');
  2175. recorderRef.current?.stop();
  2176. resetFrequencyVisualization();
  2177. // 清理解码中的情绪状态与 GIF 切换定时器
  2178. pendingEmotionRef.current = null;
  2179. if (emotionGifTimerRef.current) {
  2180. clearTimeout(emotionGifTimerRef.current);
  2181. emotionGifTimerRef.current = null;
  2182. }
  2183. // 恢复默认头像 GIF
  2184. showDefaultGif();
  2185. performanceLogger.clearRequest(currentRequestId, 'websocket_unready_before_send');
  2186. reset();
  2187. return;
  2188. }
  2189. // 检查 WebSocket 状态:如果正在连接中或已就绪,允许发送
  2190. const isConnecting = wsRef.current.isConnecting();
  2191. const isReady = wsRef.current.isReady();
  2192. // 如果既不在连接中,也不已就绪,且 isConnected 为 false,说明连接失败
  2193. if (!isConnecting && !isReady && !isConnected) {
  2194. // 静默处理:语音服务未连接
  2195. debugLog('[SendGuard] 语音服务未连接');
  2196. recorderRef.current?.stop();
  2197. resetFrequencyVisualization();
  2198. // 清理解码中的情绪状态与 GIF 切换定时器
  2199. pendingEmotionRef.current = null;
  2200. if (emotionGifTimerRef.current) {
  2201. clearTimeout(emotionGifTimerRef.current);
  2202. emotionGifTimerRef.current = null;
  2203. }
  2204. // 恢复默认头像 GIF
  2205. showDefaultGif();
  2206. performanceLogger.clearRequest(currentRequestId, 'websocket_disconnected_before_send');
  2207. reset();
  2208. return;
  2209. }
  2210. // 如果正在连接中或已就绪,允许发送(消息会被缓冲)
  2211. timingRef.current.recordEnd = Date.now();
  2212. sendTimeRef.current = Date.now();
  2213. performanceLogger.recordEnd(currentRequestId, chunkIndexRef.current);
  2214. // 计算说话时长(毫秒)
  2215. const speechDuration = timingRef.current.recordEnd - timingRef.current.recordStart;
  2216. // 进度条与累计说话时长以后端为准:
  2217. // 这里只负责将本次说话时长发送给后端,不在前端进行乐观更新,
  2218. // 后端在成功处理并持久化 total_speech_duration_ms 后,会通过 totalDurationMs 同步最新进度。
  2219. if (speechDuration > 0 && shouldSkipProgressAnimationRef.current) {
  2220. debugLog('[Progress] [handleSend] 初始化阶段结束,后续进度同步以后端为准', {
  2221. speechDurationMs: speechDuration,
  2222. });
  2223. shouldSkipProgressAnimationRef.current = false;
  2224. }
  2225. recorderRef.current?.stop();
  2226. resetFrequencyVisualization();
  2227. // 发送音频结束消息,包含说话时长信息
  2228. wsRef.current?.sendAudioEnd(currentRequestId, chunkIndexRef.current, speechDuration);
  2229. setState('sending');
  2230. // 设置超时保护:10秒后如果还在 sending 或 playing 状态,自动重置
  2231. if (sendingTimeoutRef.current) {
  2232. clearTimeout(sendingTimeoutRef.current);
  2233. }
  2234. sendingTimeoutRef.current = window.setTimeout(() => {
  2235. const state = useAppStore.getState().currentState;
  2236. if (state === 'sending' || state === 'playing') {
  2237. const shortId = currentRequestId ? currentRequestId.substring(0, 8) : '';
  2238. console.warn(`[超时] [${shortId}] 响应超时,自动重置`);
  2239. // 静默处理超时提示
  2240. debugLog('[Timeout] 响应超时,自动重置');
  2241. // 清理解码中的情绪状态与 GIF 切换定时器
  2242. pendingEmotionRef.current = null;
  2243. if (emotionGifTimerRef.current) {
  2244. clearTimeout(emotionGifTimerRef.current);
  2245. emotionGifTimerRef.current = null;
  2246. }
  2247. // 恢复默认头像 GIF
  2248. showDefaultGif();
  2249. setState('idle');
  2250. reset();
  2251. performanceLogger.clearRequest(currentRequestId, '响应超时');
  2252. }
  2253. }, 10000);
  2254. };
  2255. handleSendRef.current = handleSend;
  2256. // 取消录音
  2257. const handleCancel = () => {
  2258. if (currentState !== 'recording' || !currentRequestId) return;
  2259. const shortId = currentRequestId.substring(0, 8);
  2260. debugLog(`[取消] [${shortId}] 取消录音`);
  2261. recorderRef.current?.stop();
  2262. resetFrequencyVisualization();
  2263. stopRecordingTimer();
  2264. // 清理解码中的情绪状态与 GIF 切换定时器
  2265. pendingEmotionRef.current = null;
  2266. if (emotionGifTimerRef.current) {
  2267. clearTimeout(emotionGifTimerRef.current);
  2268. emotionGifTimerRef.current = null;
  2269. }
  2270. // 恢复默认头像 GIF
  2271. showDefaultGif();
  2272. wsRef.current?.sendCancel(currentRequestId);
  2273. cancelledRequestIdsRef.current.add(currentRequestId);
  2274. performanceLogger.clearRequest(currentRequestId);
  2275. reset();
  2276. };
  2277. const avatarHintSize = Math.round(layout.avatarCSize * 1.8);
  2278. const currentAvatarAlt = currentState === 'playing' ? 'AnimaZone Avatar Animated' : 'AnimaZone Avatar';
  2279. const energyStoneAssets: Record<'mission' | 'conversation', string> = {
  2280. mission: missionEnergyStone,
  2281. conversation: conversationEnergyStone,
  2282. };
  2283. const energyStoneHintAssets: Record<'mission' | 'conversation', string> = {
  2284. mission: missionEnergyStoneHint,
  2285. conversation: conversationEnergyStoneHint,
  2286. };
  2287. const handleEnergyStoneSpawn = useCallback(
  2288. (payload: EnergyStoneSpawnMessage) => {
  2289. spawnStone(payload);
  2290. },
  2291. [spawnStone]
  2292. );
  2293. // 获取用户名的首字母(英文大写,汉字保持原样)
  2294. const getUserInitial = (): string => {
  2295. const userName = getStorage(STORAGE_KEYS.USER_NAME);
  2296. if (!userName || userName.length === 0) {
  2297. return '';
  2298. }
  2299. const firstChar = userName[0];
  2300. // 判断是否为英文字母
  2301. if (/[a-zA-Z]/.test(firstChar)) {
  2302. return firstChar.toUpperCase();
  2303. }
  2304. // 汉字或其他字符保持原样
  2305. return firstChar;
  2306. };
  2307. // 根据背景图片获取对应的树木装饰图片URL
  2308. const getTreesImage = (): string | null => {
  2309. // 实时从 localStorage 读取最新的背景图片URL,使用背景图片作为树木装饰
  2310. const currentBgUrl = getCurrentBackgroundImageUrl() || backgroundImageUrl;
  2311. return currentBgUrl;
  2312. };
  2313. // 根据背景图片ID获取树木装饰图片的样式配置
  2314. const getTreesImageStyle = (): React.CSSProperties => {
  2315. const baseStyle: React.CSSProperties = {
  2316. width: '100%',
  2317. height: '100%',
  2318. top: 0,
  2319. left: 0,
  2320. objectFit: 'cover',
  2321. zIndex: 1,
  2322. };
  2323. // 从 localStorage 读取透明度配置(从数据库metadata中获取)
  2324. const opacity = getCurrentBackgroundImageOpacity();
  2325. return { ...baseStyle, opacity };
  2326. };
  2327. const userInitial = getUserInitial();
  2328. // 计算 Avatar-C 头像的显示逻辑
  2329. const isLoggedIn = getStorage(STORAGE_KEYS.IS_LOGGED_IN) === 'true';
  2330. // 图片选择:未登录或已登录且已分享 → avatarC,已登录且未分享 → avatarGift
  2331. const avatarSrc = (!isLoggedIn || hasSharedAvatar) ? avatarC : avatarGift;
  2332. // 首字母显示:未登录或已登录且已分享 → 显示,已登录且未分享 → 不显示
  2333. const shouldShowInitial = userInitial && (!isLoggedIn || hasSharedAvatar);
  2334. return (
  2335. <div
  2336. style={{
  2337. position: 'relative',
  2338. width: '100%',
  2339. minHeight: '100dvh',
  2340. }}
  2341. >
  2342. {/* 树木装饰 - 根据背景图片调整图片和样式 */}
  2343. {getTreesImage() && (
  2344. <img
  2345. src={getTreesImage() || undefined}
  2346. alt="Trees"
  2347. className="chatbot-trees absolute pointer-events-none"
  2348. style={getTreesImageStyle()}
  2349. />
  2350. )}
  2351. {/* Avatar-C 头像 - 设计稿:top 63px, right 33px, 尺寸 40×40,使用 px2vmin 等比缩放 */}
  2352. <div
  2353. className="chatbot-avatar-c absolute"
  2354. data-avatar-state={isAvatarCUnlocked ? 'unlocked' : 'locked'}
  2355. role={isAvatarCUnlocked ? 'button' : undefined}
  2356. tabIndex={isAvatarCUnlocked ? 0 : -1}
  2357. aria-label={isAvatarCUnlocked ? 'Avatar C' : undefined}
  2358. onClick={isAvatarCUnlocked ? handleAvatarClick : undefined}
  2359. onKeyDown={isAvatarCUnlocked ? handleAvatarKeyDown : undefined}
  2360. style={{
  2361. width: px2vmin(40),
  2362. height: px2vmin(40),
  2363. top: px2vmin(63),
  2364. right: px2vmin(33),
  2365. zIndex: hasSharedAvatar ? 5 : 30,
  2366. pointerEvents: isAvatarCUnlocked ? 'auto' : 'none',
  2367. cursor: isAvatarCUnlocked ? 'pointer' : 'default',
  2368. }}
  2369. >
  2370. {isAvatarCUnlocked && (
  2371. <img
  2372. src={avatarHint}
  2373. alt="Avatar Hint"
  2374. className="chatbot-avatar-hint"
  2375. style={{
  2376. width: `${avatarHintSize}px`,
  2377. height: `${avatarHintSize}px`,
  2378. }}
  2379. />
  2380. )}
  2381. <img
  2382. src={avatarSrc}
  2383. alt="Avatar C"
  2384. className="rounded-full"
  2385. style={{
  2386. width: '100%',
  2387. height: '100%',
  2388. opacity: isAvatarCUnlocked ? 1 : 0.2,
  2389. transition: 'opacity 0.4s ease',
  2390. position: 'relative',
  2391. zIndex: hasSharedAvatar ? 1 : 30,
  2392. }}
  2393. />
  2394. {shouldShowInitial && (
  2395. <div
  2396. style={{
  2397. position: 'absolute',
  2398. top: '50%',
  2399. left: '50%',
  2400. transform: 'translate(-50%, -50%)',
  2401. backgroundImage: 'linear-gradient(180deg, #25232E 0%, #2B2A2F 100%)',
  2402. WebkitBackgroundClip: 'text',
  2403. backgroundClip: 'text',
  2404. WebkitTextFillColor: 'transparent',
  2405. color: 'transparent',
  2406. fontSize: px2vmin(16),
  2407. fontWeight: 600,
  2408. opacity: 0.9,
  2409. pointerEvents: 'none',
  2410. zIndex: 31,
  2411. }}
  2412. >
  2413. {userInitial}
  2414. </div>
  2415. )}
  2416. </div>
  2417. {/* 隐藏的能量石容器 - 用于 useEnergyStones hook 计算位置 */}
  2418. <div
  2419. ref={hiddenEnergyStoneZoneRef}
  2420. style={{
  2421. position: 'absolute',
  2422. width: px2vmin(343), // 设计稿 343px,基于 vw/vh 最小值
  2423. height: px2vmin(172), // 设计稿 172px,基于 vw/vh 最小值
  2424. top: px2vmin(126), // 设计稿 top 126px,基于 vw/vh 最小值
  2425. left: '50%',
  2426. transform: 'translateX(-50%)',
  2427. visibility: 'hidden',
  2428. pointerEvents: 'none',
  2429. zIndex: -1,
  2430. }}
  2431. />
  2432. {/* 能量石展示区域 - 已废弃,能量石现在独立定位,不再嵌套在此容器中 */}
  2433. {/* <div
  2434. className="chatbot-energy-zone absolute"
  2435. style={{
  2436. width: px2vmin(343), // 设计稿 343px,基于 vw/vh 最小值
  2437. height: px2vmin(172), // 设计稿 172px,基于 vw/vh 最小值
  2438. top: px2vmin(126), // 设计稿 top 126px,基于 vw/vh 最小值
  2439. left: '50%',
  2440. transform: 'translateX(-50%)',
  2441. zIndex: 4,
  2442. pointerEvents: 'none',
  2443. }}
  2444. >
  2445. <div className="energy-stone-layer" />
  2446. </div> */}
  2447. {/* 正式能量石 - 独立绝对定位,限制在能量石区域内 */}
  2448. {energyStones.map((stone) => {
  2449. const asset = energyStoneAssets[stone.stoneType];
  2450. const hintAsset = energyStoneHintAssets[stone.stoneType];
  2451. const stoneSize = 48; // 设计稿 48px,基于 vw/vh 最小值
  2452. const hintSize = 92; // 设计稿 92px,基于 vw/vh 最小值
  2453. const shouldShowHint = stone.stoneType === 'mission'
  2454. ? !hasClickedMissionStone
  2455. : !hasClickedConversationStone;
  2456. // 计算绝对位置:基于能量石区域的边界
  2457. // 区域:left 50% translateX(-50%), top: px2vmin(126), width: px2vmin(343), height: px2vmin(172)
  2458. // 能量石在区域内的百分比位置转换为绝对位置
  2459. // left: 50% + (xRatio - 0.5) * zoneWidth
  2460. // top: zoneTop + yRatio * zoneHeight
  2461. const zoneTop = px2vmin(126);
  2462. const zoneWidth = px2vmin(343);
  2463. const zoneHeight = px2vmin(172);
  2464. const absoluteLeft = `calc(50% + (${stone.position.xRatio} - 0.5) * ${zoneWidth})`;
  2465. const absoluteTop = `calc(${zoneTop} + ${stone.position.yRatio} * ${zoneHeight})`;
  2466. return (
  2467. <div
  2468. key={stone.stoneId}
  2469. data-stone-id={stone.stoneId}
  2470. data-fading={stone.fading ? 'true' : 'false'}
  2471. className={`energy-stone-container ${stone.stoneType === 'mission' ? 'energy-stone-mission' : ''}`}
  2472. style={{
  2473. position: 'absolute',
  2474. left: absoluteLeft,
  2475. top: absoluteTop,
  2476. transform: 'translate(-50%, -50%)',
  2477. width: px2vmin(stoneSize),
  2478. height: px2vmin(stoneSize),
  2479. pointerEvents: 'auto',
  2480. cursor: 'pointer',
  2481. zIndex: 5,
  2482. }}
  2483. >
  2484. {/* 光晕层 - 只在未点击时显示,但在动画过程中也显示以跟随能量石 */}
  2485. {shouldShowHint && (
  2486. <img
  2487. src={hintAsset}
  2488. alt=""
  2489. className="energy-stone-hint"
  2490. style={{
  2491. position: 'absolute',
  2492. top: '50%',
  2493. left: '50%',
  2494. transform: 'translate(-50%, -50%)',
  2495. transformOrigin: 'center center',
  2496. width: px2vmin(hintSize),
  2497. height: px2vmin(hintSize),
  2498. pointerEvents: 'none',
  2499. zIndex: 0,
  2500. opacity: stone.fading ? 0 : undefined, // 动画过程中逐渐消失
  2501. maxWidth: 'none',
  2502. maxHeight: 'none',
  2503. objectFit: 'contain',
  2504. }}
  2505. />
  2506. )}
  2507. {/* 能量石按钮 */}
  2508. <button
  2509. type="button"
  2510. className="energy-stone"
  2511. data-type={stone.stoneType}
  2512. data-fading={stone.fading ? 'true' : 'false'}
  2513. style={{
  2514. position: 'absolute',
  2515. top: '50%',
  2516. left: '50%',
  2517. transform: 'translate(-50%, -50%)',
  2518. transformOrigin: 'center center',
  2519. width: px2vmin(stoneSize),
  2520. height: px2vmin(stoneSize),
  2521. zIndex: stone.fading ? 100 : 1,
  2522. pointerEvents: stone.fading ? 'none' : 'auto',
  2523. }}
  2524. onClick={async () => {
  2525. // 更新点击状态(控制光晕显示)
  2526. const clickedStorageKey = stone.stoneType === 'mission'
  2527. ? STORAGE_KEYS.HAS_CLICKED_MISSION_STONE
  2528. : STORAGE_KEYS.HAS_CLICKED_CONVERSATION_STONE;
  2529. const hasClicked = getStorage(clickedStorageKey);
  2530. const isFirstClick = hasClicked !== 'true';
  2531. // 检查是否是第一次点击,决定是否显示弹窗
  2532. const storageKey = stone.stoneType === 'mission'
  2533. ? STORAGE_KEYS.HAS_SHOWN_MISSION_STONE_MODAL
  2534. : STORAGE_KEYS.HAS_SHOWN_CONVERSATION_STONE_MODAL;
  2535. const hasShown = getStorage(storageKey);
  2536. const isFirstShowModal = hasShown !== 'true';
  2537. // 更新点击状态(控制光晕显示)
  2538. if (isFirstClick) {
  2539. setStorage(clickedStorageKey, 'true');
  2540. if (stone.stoneType === 'mission') {
  2541. setHasClickedMissionStone(true);
  2542. } else {
  2543. setHasClickedConversationStone(true);
  2544. }
  2545. }
  2546. // 准备需要同步到数据库的字段
  2547. const userId = getUserId();
  2548. const updatePayload: Record<string, boolean> = {};
  2549. // 如果是第一次点击,需要更新点击状态
  2550. if (isFirstClick) {
  2551. if (stone.stoneType === 'mission') {
  2552. updatePayload.has_clicked_mission_stone = true;
  2553. } else {
  2554. updatePayload.has_clicked_conversation_stone = true;
  2555. }
  2556. }
  2557. // 如果是第一次显示弹窗,需要更新弹窗状态
  2558. if (isFirstShowModal) {
  2559. setEnergyStoneModalType(stone.stoneType);
  2560. setShowMissionStoneModal(true);
  2561. pendingStoneIdRef.current = stone.stoneId;
  2562. if (stone.stoneType === 'mission') {
  2563. updatePayload.has_shown_mission_stone_modal = true;
  2564. } else {
  2565. updatePayload.has_shown_conversation_stone_modal = true;
  2566. }
  2567. }
  2568. // 非首次弹窗,直接播放动画并移除能量石
  2569. if (!isFirstShowModal) {
  2570. startStoneAnimationAndRemove(stone.stoneId);
  2571. }
  2572. // 合并同步到数据库(一次性更新所有需要更新的字段)
  2573. if (userId && Object.keys(updatePayload).length > 0) {
  2574. try {
  2575. await updateUserUIState(userId, updatePayload);
  2576. debugLog('[能量石] 能量石状态已同步到数据库:', updatePayload);
  2577. // 同步成功后更新 localStorage
  2578. if (isFirstShowModal) {
  2579. setStorage(storageKey, 'true');
  2580. }
  2581. } catch (error) {
  2582. console.error('同步能量石状态到数据库失败:', error);
  2583. // 同步失败时,如果只是点击状态失败,不影响弹窗显示
  2584. // 但如果是弹窗状态失败,需要回滚弹窗显示
  2585. if (isFirstShowModal) {
  2586. // 弹窗已经显示,但同步失败,记录错误以便后续补偿
  2587. console.warn('[能量石] 弹窗状态同步失败,但弹窗已显示');
  2588. }
  2589. }
  2590. } else if (!userId) {
  2591. // 没有 userId(游客态),仅更新本地
  2592. if (isFirstShowModal) {
  2593. setStorage(storageKey, 'true');
  2594. }
  2595. debugLog('[能量石] 游客状态,仅更新本地,等待后续补偿同步');
  2596. } else {
  2597. // 没有需要更新的字段,直接更新 localStorage(如果显示弹窗)
  2598. if (isFirstShowModal) {
  2599. setStorage(storageKey, 'true');
  2600. }
  2601. }
  2602. }}
  2603. aria-label={stone.stoneType === 'mission' ? '任务能量石' : '对话能量石'}
  2604. >
  2605. <img src={asset} alt="" aria-hidden="true" />
  2606. </button>
  2607. </div>
  2608. );
  2609. })}
  2610. {/* AnimaZone 头像 - 使用设计稿 375×812 基准 + px2vmin 适配 */}
  2611. <div
  2612. className="chatbot-anima-zone-avatar absolute"
  2613. style={{
  2614. // 设计稿宽 343px,高 340px,基于 vw/vh 的最小值等比缩放
  2615. width: px2vmin(343),
  2616. height: px2vmin(340),
  2617. // 设计稿 top 248px,同样基于 vw/vh 的最小值
  2618. top: px2vmin(248),
  2619. left: '50%',
  2620. transform: 'translateX(-50%)',
  2621. opacity: 1,
  2622. zIndex: 2,
  2623. }}
  2624. >
  2625. <img
  2626. src={currentAvatarGif}
  2627. alt={currentAvatarAlt}
  2628. loading="eager"
  2629. decoding="sync"
  2630. style={{
  2631. width: '100%',
  2632. height: '100%',
  2633. objectFit: 'contain',
  2634. pointerEvents: 'none',
  2635. }}
  2636. />
  2637. </div>
  2638. {/* Yp 图片 - 位于动画形象下方 */}
  2639. <div
  2640. className="absolute"
  2641. style={{
  2642. top: `calc(${px2vmin(248)} + ${px2vmin(302)})`,
  2643. left: '50%',
  2644. transform: 'translateX(-50%)',
  2645. width: px2vmin(113),
  2646. height: px2vmin(18),
  2647. zIndex: 10,
  2648. }}
  2649. >
  2650. <img
  2651. src={YpImage}
  2652. alt="Yp"
  2653. className="w-full h-full object-contain"
  2654. style={{ width: '100%', height: '100%' }}
  2655. draggable={false}
  2656. />
  2657. </div>
  2658. {/* 音频波形 - 宽度 100% 自适应 */}
  2659. <div
  2660. className="chatbot-audio-wave overflow-hidden"
  2661. style={{
  2662. // 相对于父容器定位,贴底
  2663. position: 'absolute',
  2664. width: '100%',
  2665. // 录音/播放时展开波形高度
  2666. height: waveformHeightStyle,
  2667. bottom: 0,
  2668. left: 0,
  2669. transition: 'height 0.3s ease-in-out',
  2670. zIndex: 10,
  2671. }}
  2672. data-expanded={shouldExpandWaveform ? 'true' : 'false'}
  2673. data-waveform-bottom={0}
  2674. >
  2675. <div
  2676. style={{
  2677. position: 'absolute',
  2678. bottom: 0,
  2679. left: 0,
  2680. width: '100%',
  2681. height: waveformHeightStyle, // 设计稿高度根据状态切换
  2682. }}
  2683. >
  2684. <AudioWave
  2685. ref={audioWaveRef}
  2686. isAnimating={currentState === 'recording'}
  2687. width={typeof window !== 'undefined' ? window.innerWidth : 375}
  2688. height={waveformHeightPx}
  2689. />
  2690. </div>
  2691. </div>
  2692. {/* 进度条+录音按钮容器 - 设计稿:top 614px,尺寸 114×114, 左右居中,使用 px2vmin 适配(基于 vw/vh 最小值) */}
  2693. {/* 容器在非录音状态显示进度环,在录音状态显示按钮 */}
  2694. <div
  2695. className="chatbot-progress-container absolute"
  2696. style={{
  2697. width: px2vmin(114), // 设计稿 114px,基于 vw/vh 最小值
  2698. height: px2vmin(114), // 设计稿 114px,基于 vw/vh 最小值
  2699. top: px2vh(614), // 设计稿 top 614px,基于 vh
  2700. left: '50%',
  2701. transform: 'translateX(-50%)',
  2702. zIndex: 20,
  2703. }}
  2704. >
  2705. {/* 进度环 - 背景层 - 只在非录音状态显示 */}
  2706. {currentState !== 'recording' && (
  2707. <div
  2708. className="chatbot-progress-ring absolute"
  2709. style={{
  2710. width: '100%',
  2711. height: '100%',
  2712. top: '1px',
  2713. left: 0,
  2714. }}
  2715. >
  2716. {/* 空状态背景 */}
  2717. <img
  2718. src={progressRing}
  2719. alt="Progress Ring"
  2720. className="pointer-events-none"
  2721. style={{
  2722. position: 'absolute',
  2723. top: px2vmin(0), // 设计稿 top 0px,基于 vw/vh 最小值
  2724. left: '-0.5PX', // 设计稿 left -0.5px,使用大写 PX 避免转换
  2725. width: '100%',
  2726. height: '100%',
  2727. opacity: 1,
  2728. zIndex: 1,
  2729. }}
  2730. />
  2731. {/* 进度填充层 - 使用 SVG + CSS Mask */}
  2732. {/* SVG Mask 显示完整进度(到 progress%) */}
  2733. {displayProgress > 0 && (
  2734. <div
  2735. className="pointer-events-none"
  2736. style={{
  2737. position: 'absolute',
  2738. top: px2vmin(0), // 设计稿 top 0px,基于 vw/vh 最小值
  2739. left: '-0.5PX', // 设计稿 left -0.5px,使用大写 PX 避免转换
  2740. width: '100%',
  2741. height: '100%',
  2742. // CSS conic-gradient mask:从 215° 开始,每 1% = 2.88 度
  2743. // 显示完整进度(到 progress%)
  2744. maskImage: `conic-gradient(from 215deg at 50% 50%, black 0deg, black ${displayProgress * 2.88}deg, transparent ${displayProgress * 2.88}deg, transparent 360deg)`,
  2745. WebkitMaskImage: `conic-gradient(from 215deg at 50% 50%, black 0deg, black ${displayProgress * 2.88}deg, transparent ${displayProgress * 2.88}deg, transparent 360deg)`,
  2746. zIndex: 2,
  2747. }}
  2748. >
  2749. <img
  2750. src={progressFull}
  2751. alt="Progress Full"
  2752. style={{
  2753. width: '100%',
  2754. height: '100%',
  2755. display: 'block',
  2756. }}
  2757. />
  2758. </div>
  2759. )}
  2760. {/* 进度条提示 - 相对于进度环定位 - 首次有进度时显示 */}
  2761. {showProgressBarTooltip && isConnected && (
  2762. <img
  2763. ref={progressBarTooltipRef}
  2764. src={tooltipsProgressBar}
  2765. alt="Progress Bar Tooltip"
  2766. className="chatbot-tooltips absolute pointer-events-none"
  2767. style={{
  2768. width: px2vmin(167), // 设计稿 width 167px,基于 vw/vh 最小值
  2769. height: px2vmin(130), // 设计稿 height 130px,基于 vw/vh 最小值
  2770. top: '-100%',
  2771. left: '-100%',
  2772. opacity: 1,
  2773. zIndex: 10,
  2774. maxWidth: 'none', // 确保不被限制
  2775. maxHeight: 'none', // 确保不被限制
  2776. }}
  2777. />
  2778. )}
  2779. </div>
  2780. )}
  2781. {/* 录音按钮 - 设计稿:尺寸 96×96,top 623px,左右居中 - 只在非录音状态显示 */}
  2782. {currentState !== 'recording' && (
  2783. <div
  2784. className={`chatbot-record-button absolute touch-manipulation ${isConnected ? 'cursor-pointer' : 'cursor-not-allowed'}`}
  2785. onClick={handleStartRecord}
  2786. style={{
  2787. width: px2vmin(96), // 设计稿 96px,基于 vw/vh 最小值
  2788. height: px2vmin(96), // 设计稿 96px,基于 vw/vh 最小值
  2789. top: '50%', // 在容器内垂直居中
  2790. left: '50%',
  2791. transform: 'translate(-50%, -50%)', // 水平和垂直居中
  2792. borderRadius: px2vw(100),
  2793. opacity: isConnected ? 1 : 0.55,
  2794. display: 'flex',
  2795. alignItems: 'center',
  2796. justifyContent: 'center',
  2797. userSelect: 'none',
  2798. WebkitUserSelect: 'none',
  2799. caretColor: 'transparent',
  2800. outline: 'none',
  2801. filter: isConnected ? 'none' : 'grayscale(0.25)',
  2802. overflow: 'visible', // 允许 tooltips 超出按钮边界
  2803. }}
  2804. contentEditable={false}
  2805. tabIndex={-1}
  2806. aria-disabled={!isConnected}
  2807. >
  2808. {/* 录音按钮背景 - PNG 图片 */}
  2809. <img
  2810. src={audioButton}
  2811. alt="Audio Button Background"
  2812. className="pointer-events-none"
  2813. style={{
  2814. width: '100%',
  2815. height: '100%',
  2816. position: 'absolute',
  2817. top: 0,
  2818. left: 0,
  2819. }}
  2820. />
  2821. {/* 麦克风图标 - 居中 - 响应式尺寸 */}
  2822. <img
  2823. src={microphoneIcon}
  2824. alt="Microphone"
  2825. className="pointer-events-none"
  2826. style={{
  2827. width: px2vmin(32),
  2828. height: px2vmin(32),
  2829. opacity: 1,
  2830. position: 'relative',
  2831. zIndex: 1,
  2832. }}
  2833. />
  2834. {/* Tap to Chat 提示 - 相对于录音按钮定位 - 只显示一次 - 在按钮内部使用绝对定位 */}
  2835. {showTapToChat && isConnected && (
  2836. <img
  2837. src={tapToChat}
  2838. alt="Tap to Chat"
  2839. className="chatbot-tooltips absolute pointer-events-none"
  2840. style={{
  2841. width: px2vmin(128), // 设计稿 width 128px,基于 vw/vh 最小值
  2842. height: px2vmin(100), // 设计稿 height 100px,基于 vw/vh 最小值
  2843. top: '-100%',
  2844. right: '-100%',
  2845. borderRadius: `${Math.round(8 * layout.avatarScale)}px`,
  2846. opacity: 1,
  2847. zIndex: 10,
  2848. maxWidth: 'none', // 确保不被限制
  2849. maxHeight: 'none', // 确保不被限制
  2850. }}
  2851. />
  2852. )}
  2853. </div>
  2854. )}
  2855. {/* 取消语音发送按钮 - 录音状态显示,与录音按钮同高度,左侧对齐 */}
  2856. {currentState === 'recording' && (
  2857. <div
  2858. className="chatbot-action-buttons absolute flex items-center justify-center cursor-pointer touch-manipulation"
  2859. onClick={handleCancel}
  2860. style={{
  2861. width: px2vmin(56), // 设计稿 width 56px,基于 vw/vh 最小值
  2862. height: px2vmin(56), // 设计稿 height 56px,基于 vw/vh 最小值
  2863. top: '50%',
  2864. left: `calc(50% - ${px2vmin(56)} / 2 - ${px2vmin(50)} / 2)`, // 按钮宽度 56px,间距 50px,基于 vw/vh 最小值
  2865. transform: 'translate(-50%, -50%)',
  2866. borderRadius: px2vw(100),
  2867. opacity: 1,
  2868. background: 'rgba(255, 255, 255, 0.1)',
  2869. backdropFilter: 'blur(15px)',
  2870. zIndex: 20,
  2871. userSelect: 'none',
  2872. WebkitUserSelect: 'none',
  2873. caretColor: 'transparent',
  2874. outline: 'none',
  2875. overflow: 'visible', // 允许 tooltip 超出按钮边界
  2876. }}
  2877. contentEditable={false}
  2878. tabIndex={-1}
  2879. >
  2880. {/* 按钮背景装饰图片 */}
  2881. <img
  2882. src={audioButton}
  2883. alt="Button Background"
  2884. className="pointer-events-none"
  2885. style={{
  2886. width: 'calc(100% + 1px)',
  2887. height: 'calc(100% + 1px)',
  2888. position: 'absolute',
  2889. top: '0',
  2890. left: '0',
  2891. }}
  2892. />
  2893. {/* Cancel 图标 - 居中 - 响应式尺寸 */}
  2894. <img
  2895. src={cancelIcon}
  2896. alt="Cancel"
  2897. className="pointer-events-none"
  2898. style={{
  2899. width: px2vmin(24),
  2900. height: px2vmin(24),
  2901. position: 'relative',
  2902. zIndex: 1,
  2903. }}
  2904. />
  2905. {/* 取消语音发送提示 - 相对于取消按钮定位 - 只在首次录音时显示 */}
  2906. {showCancelTooltip && (
  2907. <img
  2908. src={tooltipsCancel}
  2909. alt="Cancel Tooltip"
  2910. className="chatbot-tooltips absolute pointer-events-none"
  2911. style={{
  2912. width: px2vmin(109), // 设计稿 width 109px,基于 vw/vh 最小值
  2913. height: px2vmin(91), // 设计稿 height 91px,基于 vw/vh 最小值
  2914. bottom: '110%',
  2915. left: '-150%',
  2916. borderRadius: px2vmin(8),
  2917. opacity: 1,
  2918. zIndex: 10,
  2919. maxWidth: 'none', // 确保不被限制
  2920. maxHeight: 'none', // 确保不被限制
  2921. }}
  2922. />
  2923. )}
  2924. </div>
  2925. )}
  2926. {/* 语音发送按钮 - 录音状态显示,与录音按钮同高度,右侧对齐 */}
  2927. {currentState === 'recording' && (
  2928. <div
  2929. className="chatbot-action-buttons absolute flex items-center justify-center cursor-pointer touch-manipulation"
  2930. onClick={handleSend}
  2931. style={{
  2932. width: px2vmin(56), // 设计稿 width 56px,基于 vw/vh 最小值
  2933. height: px2vmin(56), // 设计稿 height 56px,基于 vw/vh 最小值
  2934. top: '50%',
  2935. left: `calc(50% + ${px2vmin(56)} / 2 + ${px2vmin(50)} / 2)`, // 按钮宽度 56px,间距 50px,基于 vw/vh 最小值
  2936. transform: 'translate(-50%, -50%)',
  2937. borderRadius: px2vw(100),
  2938. opacity: 1,
  2939. background: 'rgba(255, 255, 255, 0.1)',
  2940. backdropFilter: 'blur(15px)',
  2941. zIndex: 20,
  2942. userSelect: 'none',
  2943. WebkitUserSelect: 'none',
  2944. caretColor: 'transparent',
  2945. outline: 'none',
  2946. overflow: 'visible', // 允许 tooltip 超出按钮边界
  2947. }}
  2948. contentEditable={false}
  2949. tabIndex={-1}
  2950. >
  2951. {/* 按钮背景装饰图片 */}
  2952. <img
  2953. src={audioButton}
  2954. alt="Button Background"
  2955. className="pointer-events-none"
  2956. style={{
  2957. width: 'calc(100% + 1px)',
  2958. height: 'calc(100% + 1px)',
  2959. position: 'absolute',
  2960. top: '0',
  2961. left: '0',
  2962. }}
  2963. />
  2964. {/* Send 图标 - 居中 - 响应式尺寸 */}
  2965. <img
  2966. src={sendIcon}
  2967. alt="Send"
  2968. className="pointer-events-none"
  2969. style={{
  2970. width: px2vmin(24),
  2971. height: px2vmin(24),
  2972. position: 'relative',
  2973. zIndex: 1,
  2974. }}
  2975. />
  2976. {/* 语音发送提示 - 相对于发送按钮定位 - 只在首次录音时显示 */}
  2977. {showSendTooltip && (
  2978. <img
  2979. src={tooltipsSend}
  2980. alt="Send Tooltip"
  2981. className="chatbot-tooltips absolute pointer-events-none"
  2982. style={{
  2983. width: px2vmin(111),
  2984. height: 'auto',
  2985. bottom: '110%',
  2986. right: '-150%',
  2987. borderRadius: px2vmin(8),
  2988. opacity: 1,
  2989. zIndex: 10,
  2990. maxWidth: 'none', // 确保不被限制
  2991. maxHeight: 'none', // 确保不被限制
  2992. }}
  2993. />
  2994. )}
  2995. </div>
  2996. )}
  2997. {/* 倒计时组件 - 只在录音50秒后(最后10秒)显示 - 与按钮上下居中,位于界面最中间 */}
  2998. {currentState === 'recording' &&
  2999. remainingTimeMs !== null &&
  3000. remainingTimeMs <= COUNTDOWN_THRESHOLD_MS && (
  3001. <div
  3002. className="chatbot-countdown absolute font-semibold"
  3003. style={{
  3004. width: px2vmin(50), // 设计稿 width 50px,基于 vw/vh 最小值
  3005. height: px2vmin(20), // 设计稿 height 20px,基于 vw/vh 最小值
  3006. top: '50%', // 在容器内垂直居中,与按钮同一水平线
  3007. left: '50%', // 在容器内水平居中
  3008. transform: 'translate(-50%, -50%)', // 水平和垂直居中
  3009. zIndex: 21,
  3010. fontSize: px2vmin(12), // 设计稿 font-size 12px,基于 vw/vh 最小值
  3011. color: 'rgba(245, 243, 240, 1)',
  3012. textShadow: '0 2px 8px rgba(0,0,0,0.55)',
  3013. letterSpacing: '0.08em',
  3014. display: 'flex',
  3015. alignItems: 'center',
  3016. justifyContent: 'center',
  3017. }}
  3018. >
  3019. {formatCountdown(remainingTimeMs)}
  3020. </div>
  3021. )}
  3022. </div>
  3023. {/* 能量石弹窗 */}
  3024. <MissionEnergyStoneModal
  3025. visible={showMissionStoneModal}
  3026. onClose={handleMissionStoneModalClose}
  3027. stoneType={energyStoneModalType}
  3028. />
  3029. </div>
  3030. );
  3031. };