index.vue 212 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381
  1. <template>
  2. <div class="pptist-student-viewer" :class="{ 'fullscreen': isFullscreen }">
  3. <!-- Loading状态显示 -->
  4. <div v-if="isLoading" class="loading-overlay">
  5. <div class="loading-content">
  6. <div class="loading-spinner"></div>
  7. <div class="loading-text">{{ lang.ssCourseLoading }}</div>
  8. </div>
  9. </div>
  10. <!-- 左侧导航栏 -->
  11. <div class="layout-content-left" v-show="type == '1' || (type == '2' && !isFollowModeActive)" :class="{ collapsed: slidePanelCollapsed }">
  12. <div class="thumbnails">
  13. <div class="viewer-header slide-header">
  14. <h3 v-show="!slidePanelCollapsed">{{ lang.ssCourseOutline }}</h3>
  15. <button class="collapse-btn" @click="slidePanelCollapsed = !slidePanelCollapsed" :title="slidePanelCollapsed ? lang.ssExpand : lang.ssCollapse" style="right: 8px;">
  16. <span v-if="slidePanelCollapsed">
  17. <img src="@/assets/img/arrow.svg">
  18. </span>
  19. <span v-else>
  20. <img src="@/assets/img/arrow.svg" style="transform: rotate(180deg);">
  21. </span>
  22. </button>
  23. </div>
  24. <div v-if="!slidePanelCollapsed" class="panel-content">
  25. <div class="thumbnail-list">
  26. <div v-for="(slide, index) in slides" :key="slide.id" class="thumbnail-item"
  27. :class="{ 'active': slideIndex === index }" @click="goToSlide(index)">
  28. <div class="label">{{ fillDigit(index + 1, 2) }}</div>
  29. <ThumbnailSlide class="thumbnail" :slide="slide" :size="168" :visible="true" @click="goToSlide(index)" />
  30. </div>
  31. </div>
  32. </div>
  33. </div>
  34. </div>
  35. <!-- 中间放映区域 -->
  36. <div class="layout-content-center">
  37. <div class="viewer-header" :class="{ 'hidden': isFullscreen }" style="display: none;">
  38. <div class="slide-title">{{ lang.ssSlidePage }} {{ slideIndex + 1 }}</div>
  39. <div class="viewer-controls">
  40. <button @click="previousSlide" :disabled="slideIndex === 0" :title="lang.ssPrevPage" v-if="!isFollowModeActive || props.type == '1'">
  41. <IconLeftTwo class="control-icon" />
  42. </button>
  43. <button @click="nextSlide" :disabled="slideIndex === slides.length - 1" :title="lang.ssNextPage" v-if="!isFollowModeActive || props.type == '1'">
  44. <IconRightTwo class="control-icon" />
  45. </button>
  46. <!-- <button @click="resetZoom" title="重置缩放">
  47. <IconUndo class="control-icon" />
  48. </button> -->
  49. <button @click="enterFullscreen" :title="lang.ssFullscreen">
  50. <IconFullScreenOne class="control-icon" />
  51. </button>
  52. <!-- 只有创建人才显示跟随模式按钮 -->
  53. <button
  54. v-if="isCreator"
  55. @click="toggleFollowMode"
  56. :class="{ 'follow-active': isFollowModeActive }"
  57. >
  58. {{ isFollowModeActive ? lang.ssFollowOff : lang.ssFollowOn }}
  59. </button>
  60. <!-- <button @click="backToEditor" class="back-btn" title="返回编辑">
  61. <IconEdit class="control-icon" />
  62. </button> -->
  63. </div>
  64. </div>
  65. <div class="viewer-canvas" ref="viewerCanvasRef">
  66. <!-- 全屏时:使用放映功能 -->
  67. <!-- <ScreenSlideList :slideWidth="slideWidth"
  68. :slideHeight="slideHeight" :animationIndex="0" :turnSlideToId="() => { }"
  69. :manualExitFullscreen="() => { }" /> -->
  70. <!-- 不全屏时:使用编辑模式的显示比例和居中逻辑 -->
  71. <div class="slide-list-wrap" ref="slideListWrapRef" :class="{'slide-list-wrap-n': !isFullscreen, 'laser-pen': laserPen }" :style="{
  72. width: isFullscreen ? '100%' : (slideWidth * canvasScale) + 'px',
  73. height: isFullscreen ? '100%' : (slideHeight * canvasScale) + 'px',
  74. left: isFullscreen ? '0' : `${(containerWidth - slideWidth * canvasScale) / 2}px`,
  75. top: isFullscreen ? '0' : `${(containerHeight - slideHeight * canvasScale) / 2}px`
  76. }" @mousemove="handleLaserMove">
  77. <div class="homework-check-box" :class="{ 'fullscreen-mode': isFullscreen, 'fs-expanded': hwBoxExpanded }" v-if="currentSlideHasIframe && !currentSlideHasBilibiliVideo && (props.type == '1' || (props.type == '2' && currentIsResultArray.can && !is_cast_screen))" :style="{
  78. top: isFullscreen ? '0' : `0`
  79. }" @click="isFullscreen && (hwBoxExpanded = !hwBoxExpanded)">
  80. <div class="homework-check-box-item" @click.stop="openChoiceQuestionDetail2(slideIndex); hwBoxExpanded = false" :class="{'active': !choiceQuestionDetailDialogOpenList.includes(slideIndex)}">
  81. <div class="homework-check-box-item-title">{{ lang.ssQuestion }}</div>
  82. </div>
  83. <div class="homework-check-box-item" @click.stop="openChoiceQuestionDetail3(slideIndex); hwBoxExpanded = false" :class="{'active': choiceQuestionDetailDialogOpenList.includes(slideIndex)}">
  84. <div class="homework-check-box-item-title">{{ lang.ssResult }}</div>
  85. </div>
  86. </div>
  87. <div class="aiBtn" ref="aiBtnRef" v-if="isQuestionFrame && hasWork && props.type == '2' && aiAssistant"
  88. :style="{ right: aiBtnPosition.x + 'px', bottom: aiBtnPosition.y + 'px' }" @click="openAiChat">
  89. <IconComment class="aiBtn-icon" />
  90. <span>{{ lang.ssAiChat }}</span>
  91. </div>
  92. <aiChat v-show="visibleAIChat" :position="aiBtnPosition" @close="visibleAIChat = false" :userid="props.userid" :workJson="myWork" :visible="visibleAIChat" :cid="props.cid" :courseid="props.courseid"/>
  93. <!-- -->
  94. <div class="viewport" v-if="false">
  95. <div class="background" :style="backgroundStyle"></div>
  96. <ScreenElement v-for="(element, index) in elementList" :key="element.id" :elementInfo="element"
  97. :elementIndex="index + 1" :animationIndex="0" :turnSlideToId="() => { }"
  98. :manualExitFullscreen="() => { }" :is-visible="slideIndex === index" />
  99. </div>
  100. <ScreenSlideList :style="{ width: isFullscreen ? '100%' : slideWidth2 * canvasScale + 'px', height: isFullscreen ? '100%' : slideHeight2 * canvasScale + 'px', margin: '0 auto' }" :slideWidth="isFullscreen ? slideWidth * canvasScale : slideWidth2 * canvasScale" :slideHeight="isFullscreen ? slideHeight * canvasScale : slideHeight2 * canvasScale"
  101. :animationIndex="0" :turnSlideToId="() => { }" :manualExitFullscreen="() => { }" :slideIndex="slideIndex" v-show="!choiceQuestionDetailDialogOpenList.includes(slideIndex)"/>
  102. <choiceQuestionDetailDialog ref="choiceQuestionDetailDialogRef" v-if="choiceQuestionDetailDialogOpenList.includes(slideIndex) && !currentSlideHasEnglishSpeaking" :roleType="props.type" :cid="props.cid" :courseid="props.courseid" :workId="workId" :workUrl="workUrl" :userId="props.userid" :courseDetail="courseDetail" :workArray="workArray" @changeWorkIndex="changeWorkIndex" v-model:visible="choiceQuestionDetailDialogOpenList" :unsubmittedStudents="unsubmittedStudents" :showData="answerTheResultRef" :slideIndex="slideIndex" :workIndex="0" :style="{ width: isFullscreen ? '100%' : slideWidth2 * canvasScale + 'px', height: isFullscreen ? '100%' : slideHeight2 * canvasScale + 'px', margin: '0 auto' }" :slideWidth="isFullscreen ? slideWidth * canvasScale : slideWidth2 * canvasScale" :slideHeight="isFullscreen ? slideHeight * canvasScale : slideHeight2 * canvasScale" :resultArray="currentIsResultArray" @setIsResultArray="setIsResultArray2" :isCreator="isCreator" @successLike="successLike" @sendMessage="sendMessage" :isFollowModeActive="isFollowModeActive"/>
  103. <SpeakingClassPanel
  104. v-else-if="choiceQuestionDetailDialogOpenList.includes(slideIndex) && currentSlideToolType === TOPIC_DISCUSSION_TOOL_TYPE"
  105. ref="speakingPanelRef"
  106. :configId="currentSlideConfigId"
  107. :slideIndex="slideIndex"
  108. :studentArray="studentArray"
  109. :courseId="props.courseid"
  110. :slideWidth="isFullscreen ? slideWidth * canvasScale : slideWidth2 * canvasScale"
  111. :slideHeight="isFullscreen ? slideHeight * canvasScale : slideHeight2 * canvasScale"
  112. :style="{ margin: '0 auto' }"
  113. />
  114. <ArticleReadingClassPanel
  115. v-else-if="choiceQuestionDetailDialogOpenList.includes(slideIndex) && currentSlideToolType === ARTICLE_READING_TOOL_TYPE"
  116. ref="articleReadingPanelRef"
  117. :configId="currentSlideConfigId"
  118. :slideIndex="slideIndex"
  119. :studentArray="studentArray"
  120. :courseId="props.courseid || ''"
  121. :slideWidth="isFullscreen ? slideWidth * canvasScale : slideWidth2 * canvasScale"
  122. :slideHeight="isFullscreen ? slideHeight * canvasScale : slideHeight2 * canvasScale"
  123. :style="{ margin: '0 auto' }"
  124. />
  125. <div class="slide-bottom" v-if="!isFullscreen">
  126. <div class="slide-bottom-center" v-if="!isFullscreen && (!isFollowModeActive || props.type == '1')">
  127. <div class="slide-bottom-center-item">
  128. <img src="@/assets/img/left-a.svg" alt="" @click="previousSlide">
  129. <div class="slide-bottom-center-item-page">
  130. <span>{{ slideIndex + 1 }}</span>
  131. <span>/</span>
  132. <span>{{ slides.length }}</span>
  133. </div>
  134. <img src="@/assets/img/right-a.svg" alt="" @click="nextSlide">
  135. </div>
  136. </div>
  137. <div class="slide-bottom-right" v-if="!isFullscreen">
  138. <Refresh class="tool-btn" v-tooltip="lang.ssRefresh" @click="handleRefreshPage" v-if="currentSlideHasIframe && !currentSlideHasEnglishSpeaking"/>
  139. <!-- <UpTwo @click="handleHomeworkSubmit" v-if="currentSlideHasIframe && !currentSlideHasBilibiliVideo && !isSubmitting" class="tool-btn upBtn" v-tooltip="lang.ssSubmitHW"/> -->
  140. <svg @click="handleHomeworkSubmit" v-if="currentSlideHasIframe && !currentSlideHasBilibiliVideo && !isSubmitting && !currentSlideHasEnglishSpeaking" class="tool-btn upBtn" v-tooltip="lang.ssSubmitHW" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
  141. <!-- Document body -->
  142. <path d="M15 10 L15 90 Q15 95 20 95 L80 95 Q85 95 85 90 L85 35 L60 10 Z"
  143. fill="none" stroke="currentColor" stroke-width="6" stroke-linejoin="round" stroke-linecap="round"/>
  144. <!-- Folded corner -->
  145. <path d="M60 10 L60 35 L85 35"
  146. fill="none" stroke="currentColor" stroke-width="6" stroke-linejoin="round" stroke-linecap="round"/>
  147. <!-- Upload arrow shaft -->
  148. <line x1="50" y1="72" x2="50" y2="45"
  149. stroke="currentColor" stroke-width="6" stroke-linecap="round"/>
  150. <!-- Arrow head -->
  151. <polyline points="37,57 50,43 63,57"
  152. fill="none" stroke="currentColor" stroke-width="6" stroke-linejoin="round" stroke-linecap="round"/>
  153. <!-- Bottom lines -->
  154. <line x1="36" y1="80" x2="64" y2="80"
  155. stroke="currentColor" stroke-width="6" stroke-linecap="round"/>
  156. <line x1="36" y1="88" x2="64" y2="88"
  157. stroke="currentColor" stroke-width="6" stroke-linecap="round"/>
  158. </svg>
  159. <IconLoading v-else-if="currentSlideHasIframe && !currentSlideHasBilibiliVideo && !currentSlideHasEnglishSpeaking" class="tool-btn loading" v-tooltip="lang.ssSubmitting"></IconLoading>
  160. <IconStopwatchStart v-if="props.type == '1' && courseDetail.userid == props.userid && isFollowModeActive" class="tool-btn" v-tooltip="lang.ssTimer" @click="timerlVisible = !timerlVisible" />
  161. <IconWrite v-if="isFollowModeActive && props.type == '1' && courseDetail.userid == props.userid" class="tool-btn" v-tooltip="lang.ssPenTool" @click="writingBoardToolVisible = true" />
  162. <!-- <IconMagic v-if="isFollowModeActive && props.type == '1' && courseDetail.userid == props.userid" class="tool-btn" v-tooltip="lang.ssLaserPen" :class="{ 'active': laserPen }" @click="toggleLaserPen" /> -->
  163. <IconTips v-if="props.type == '1' && props.userid != 'undefined'" class="tool-btn" v-tooltip="lang.ssAiHelper" :class="{ 'active': !workPanelCollapsed }" @click="workPanelCollapsed = !workPanelCollapsed" />
  164. <IconFullScreenOne class="tool-btn" v-tooltip="lang.ssOpenFull" @click="enterFullscreen" />
  165. </div>
  166. </div>
  167. </div>
  168. <!-- 全屏时的左右下角工具按钮 -->
  169. <div v-if="isFullscreen && (!isFollowModeActive || props.type == '1')" class="tools-left">
  170. <IconLeftTwo class="tool-btn" theme="two-tone" :fill="['#111', '#fff']" @click="previousSlide" />
  171. <IconRightTwo class="tool-btn" theme="two-tone" :fill="['#111', '#fff']" @click="nextSlide" />
  172. </div>
  173. <!-- 作业提交按钮 - 当当前幻灯片包含iframe时显示(排除B站视频) -->
  174. <div v-if="currentSlideHasIframe && !currentSlideHasBilibiliVideo && isFullscreen && !currentSlideHasEnglishSpeaking" class="homework-submit-btn" :class="{ 'submitting': isSubmitting }"
  175. :style="{ right: getHomeworkButtonRight() + 'px' }" @click="handleHomeworkSubmit"
  176. v-tooltip="isSubmitting ? lang.ssHwSubmitting : lang.ssHwSubmit">
  177. <!-- <IconEdit v-if="!isSubmitting" class="tool-btn" />
  178. <div v-else class="loading-spinner"></div> -->
  179. <span class="btn-text">{{ isSubmitting ? lang.ssSubmittingEll : lang.ssSubmit }}</span>
  180. </div>
  181. <!-- 刷新iframe按钮 -->
  182. <div class="refresh-page-btn"
  183. v-if="currentSlideHasIframe && isFullscreen && !currentSlideHasEnglishSpeaking"
  184. :style="{ right: getRefreshButtonRight() + 'px' }"
  185. @click="handleRefreshPage"
  186. v-tooltip="lang.ssRefreshIframe">
  187. <Refresh class="tool-btn" />
  188. <span class="btn-text">{{ lang.ssRefresh }}</span>
  189. </div>
  190. <!-- 功能组件 -->
  191. <SlideThumbnails v-if="slideThumbnailModelVisible" :turnSlideToIndex="goToSlide"
  192. @close="slideThumbnailModelVisible = false" />
  193. <WritingBoardTool
  194. :slideWidth="slideWidth"
  195. :slideHeight="slideHeight"
  196. v-if="writingBoardToolVisible || (props.type == '2' && isFollowModeActive && writingBoardSyncDataURL && writingBoardSyncDataURL.trim() !== '')"
  197. :readonly="props.type == '2'"
  198. :syncDataURL="props.type == '2' ? writingBoardSyncDataURL : null"
  199. :syncBlackboard="props.type == '2' ? writingBoardSyncBlackboard : null"
  200. @close="handleWritingBoardClose"
  201. @drawing-end="handleDrawingEnd"
  202. @blackboard-change="handleBlackboardChange"
  203. />
  204. <CountdownTimer
  205. v-if="timerlVisible"
  206. @close="timerlVisible = false"
  207. @timer-start="onTimerStart"
  208. @timer-pause="onTimerPause"
  209. @timer-reset="onTimerReset"
  210. @timer-stop="onTimerStop"
  211. @timer-finish="onTimerFinish"
  212. @timer-update="onTimerUpdate"
  213. />
  214. <div v-if="isFullscreen && (!isFollowModeActive || props.type == '1')" class="tools-right" :class="{ 'visible': rightToolsVisible }"
  215. @mouseleave="rightToolsVisible = false" @mouseenter="rightToolsVisible = true">
  216. <div class="content">
  217. <div class="tool-btn page-number" @click="slideThumbnailModelVisible = true">
  218. {{ lang.ssSlidePage }} {{slideIndex + 1}} / {{slides.length}}
  219. </div>
  220. <IconWrite class="tool-btn" v-if="isFollowModeActive && props.type == '1' && courseDetail.userid == props.userid" v-tooltip="lang.ssPenTool" @click="writingBoardToolVisible = true" />
  221. <IconMagic class="tool-btn" v-if="isFollowModeActive && props.type == '1' && courseDetail.userid == props.userid" v-tooltip="lang.ssLaserPen" :class="{ 'active': laserPen }" @click="toggleLaserPen" />
  222. <IconStopwatchStart v-if="(props.type == '1' && courseDetail.userid == props.userid && isFollowModeActive)" class="tool-btn" v-tooltip="lang.ssTimer" @click="timerlVisible = !timerlVisible" />
  223. <IconOffScreenOne class="tool-btn" v-tooltip="lang.ssExitFull" @click="enterFullscreen" />
  224. </div>
  225. </div>
  226. </div>
  227. </div>
  228. <div class="layout-content-right" v-show="type == '1' && props.userid != 'undefined'" :class="{ collapsed: workPanelCollapsed }">
  229. <div class="thumbnails">
  230. <div class="viewer-header right-panel-header">
  231. <button class="collapse-btn" @click="workPanelCollapsed = !workPanelCollapsed" :title="workPanelCollapsed ? lang.ssExpand : lang.ssCollapse" v-if="rightPanelMode != ''" style="left: 8px;">
  232. <span v-if="workPanelCollapsed">
  233. <img src="@/assets/img/arrow.svg" style="transform: rotate(180deg);">
  234. </span>
  235. <span v-else>
  236. <img src="@/assets/img/arrow.svg">
  237. </span>
  238. </button>
  239. <!-- 标签页切换按钮 -->
  240. <div v-show="!workPanelCollapsed" class="tab-switcher">
  241. <!-- <button
  242. v-if="currentSlideHasIframe && !currentSlideHasBilibiliVideo"
  243. v-show="currentSlideHasIframe"
  244. class="tab-btn"
  245. :class="{ active: rightPanelMode === 'homework' }"
  246. @click="switchToHomework"
  247. :title="lang.ssAnswerRes"
  248. >
  249. {{ lang.ssAnswerRes }}
  250. </button> -->
  251. <button
  252. class="tab-btn"
  253. :class="{ active: rightPanelMode === 'dialogue' }"
  254. @click="switchToDialogue"
  255. :title="lang.ssDialogArea"
  256. >
  257. {{ lang.ssDialogArea }}
  258. </button>
  259. <!-- <button
  260. v-if="isChoiceQuestion"
  261. class="tab-btn"
  262. :class="{ active: rightPanelMode === 'choice' }"
  263. @click="switchToChoice"
  264. title="统计"
  265. >
  266. 统计
  267. </button> -->
  268. </div>
  269. </div>
  270. <!-- 侧边导航标签 - 无论展开还是收缩都显示在左侧 -->
  271. <!-- <div class="side-nav-tabs">
  272. <button
  273. v-if="currentSlideHasIframe"
  274. class="side-nav-btn"
  275. :class="{ active: rightPanelMode === 'homework' }"
  276. @click="switchToHomework"
  277. title="作业"
  278. >
  279. <img :src="rightPanelMode === 'homework' ? homeworkActiveIcon : homeworkIcon" alt="作业">
  280. </button>
  281. <button
  282. v-if="isChoiceQuestion"
  283. class="side-nav-btn"
  284. :class="{ active: rightPanelMode === 'choice' }"
  285. @click="switchToChoice"
  286. title="统计"
  287. >
  288. <img :src="rightPanelMode === 'choice' ? choiceActiveIcon : choiceIcon" alt="统计">
  289. </button>
  290. <button
  291. class="side-nav-btn"
  292. :class="{ active: rightPanelMode === 'dialogue' }"
  293. @click="switchToDialogue"
  294. title="对话"
  295. >
  296. <img :src="rightPanelMode === 'dialogue' ? dialogueActiveIcon : dialogueIcon" alt="对话">
  297. </button>
  298. </div> -->
  299. <!-- 回答结果内容 -->
  300. <div v-show="!workPanelCollapsed && rightPanelMode === 'homework'" class="panel-content">
  301. <div v-if="workLoading" class="homework-loading">{{ lang.ssHwLoading }}</div>
  302. <answerTheResult :toolType="toolType" :workId="workId" :workArray="workArray" :unsubmittedStudents="unsubmittedStudents" :slideIndex="slideIndex" v-else ref="answerTheResultRef" @openChoiceQuestionDetail="openChoiceQuestionDetail" @openWorkModal="openWorkModal"/>
  303. <!--<div class="homework-title">已提交</div>
  304. <div v-if="workLoading" class="homework-loading">正在加载作业...</div>
  305. <div v-else>
  306. <div v-if="workArray && workArray.length" class="homework-grid">
  307. <button class="homework-btn" v-for="(work, idx) in workArray" :key="work.id ?? idx" :title="work.name" @click="openWorkModal(work)">
  308. <span class="homework-btn__text">{{ work.name }}</span>
  309. </button>
  310. </div>
  311. <div class="homework-empty" v-else>
  312. 暂无作业提交
  313. </div>
  314. </div>-->
  315. <!--<div v-if="unsubmittedStudents && unsubmittedStudents.length > 0" class="homework-title" style="margin-top: 20px;">未提交</div>
  316. <div v-if="unsubmittedStudents && unsubmittedStudents.length > 0">
  317. <div v-if="studentLoading" class="homework-loading">正在加载学生信息...</div>
  318. <div v-else>
  319. <div class="homework-grid">
  320. <button class="homework-btn unsubmitted" v-for="(student, idx) in unsubmittedStudents" :key="student.id ?? idx" :title="student.name" disabled>
  321. <span class="homework-btn__text">{{ student.name }}</span>
  322. </button>
  323. </div>
  324. </div>
  325. </div>-->
  326. </div>
  327. <!-- 对话区内容 -->
  328. <div v-show="!workPanelCollapsed && rightPanelMode === 'dialogue'" class="panel-content">
  329. <DialoguePanel :userid="props.userid" :courseid="props.courseid" :fileid="pptJsonFileid"/>
  330. </div>
  331. <!-- 选择题统计内容 -->
  332. <div v-show="!workPanelCollapsed && rightPanelMode === 'choice'" class="panel-content">
  333. <ChoiceStatistics :workArray="workArray" :elementList="elementList" />
  334. </div>
  335. </div>
  336. </div>
  337. <!-- 右上角计时状态指示器(块状样式) -->
  338. <div
  339. v-if="timerIndicator.visible"
  340. class="timer-indicator"
  341. :class="{ 'countdown': timerIndicator.isCountdown, 'timeout': timerIndicator.isCountdown && timerIndicator.remainingSec !== null && timerIndicator.remainingSec <= 0 }"
  342. :style="{ right: getTimerIndicatorRight() + 'px', top: isFullscreen ? '16px' : '12px' }"
  343. >
  344. <div class="blocks">
  345. <template v-if="timerBlocksVisibility().showH">
  346. <span class="block">{{ timerBlocks().h }}</span>
  347. <span class="colon"></span>
  348. </template>
  349. <template v-if="timerBlocksVisibility().showM">
  350. <span class="block">{{ timerBlocks().m }}</span>
  351. <span class="colon"></span>
  352. </template>
  353. <span class="block">{{ timerBlocks().s }}</span>
  354. </div>
  355. </div>
  356. </div>
  357. <ShotWorkModal v-model:visible="visibleShot" :work="selectedWork" />
  358. <QAWorkModal v-model:visible="visibleQA" :work="selectedWork" />
  359. <ChoiceWorkModal v-model:visible="visibleChoice" :work="selectedWork" />
  360. <AIWorkModal v-model:visible="visibleAI" :work="selectedWork" />
  361. <!-- 学生端激光笔覆盖层(拦截点击) -->
  362. <div
  363. v-if="props.type == '2' && laserPenOverlay.visible"
  364. class="laser-pointer-overlay"
  365. :style="laserOverlayStyle"
  366. >
  367. <div class="laser-pointer-dot" ref="laserDotRef"></div>
  368. </div>
  369. <!-- 在适当位置添加连接状态指示器 -->
  370. <div class="connection-status" v-if="connectionStatus !== 'connected'">
  371. <div class="status-indicator" :class="connectionStatus">
  372. <span v-if="connectionStatus === 'connecting'">{{ lang.ssConnecting }}</span>
  373. <span v-else-if="connectionStatus === 'disconnected'">{{ lang.ssConnLost }}</span>
  374. </div>
  375. <button v-if="connectionStatus === 'disconnected'" @click="manualReconnect" class="reconnect-btn">
  376. {{ lang.ssReconnect }}
  377. </button>
  378. </div>
  379. <div class="connection-status" v-if="false">
  380. <div class="status-indicator" :class="'disconnected'">
  381. <span>{{ lang.ssConnLost }}</span>
  382. </div>
  383. <button @click="manualReconnect" class="reconnect-btn">
  384. {{ lang.ssReconnect }}
  385. </button>
  386. </div>
  387. <messageInstruction ref="messageInstructionRef" />
  388. </template>
  389. <script lang="ts" setup>
  390. import { computed, ref, onMounted, onUnmounted, nextTick, inject, watch, provide, shallowRef } from 'vue'
  391. import { storeToRefs } from 'pinia'
  392. import { useSlidesStore } from '@/store'
  393. import { ElementTypes } from '@/types/slides'
  394. import { fillDigit } from '@/utils/common'
  395. import ThumbnailSlide from '@/views/components/ThumbnailSlide/index.vue'
  396. import ScreenSlideList from '@/views/Screen/ScreenSlideList.vue'
  397. import ScreenElement from '@/views/Screen/ScreenElement.vue'
  398. import SlideThumbnails from '@/views/Screen/SlideThumbnails.vue'
  399. import WritingBoardTool from '@/views/Screen/WritingBoardTool.vue'
  400. import CountdownTimer from '@/views/Screen/CountdownTimer.vue'
  401. import useSlideBackgroundStyle from '@/hooks/useSlideBackgroundStyle'
  402. import useImport from '@/hooks/useImport'
  403. import message from '@/utils/message'
  404. import api, { API_URL } from '@/services/course'
  405. import axios from '@/services/config'
  406. import {currentVersion, lang} from '@/main'
  407. import ShotWorkModal from './components/ShotWorkModal.vue'
  408. import QAWorkModal from './components/QAWorkModal.vue'
  409. import ChoiceWorkModal from './components/ChoiceWorkModal.vue'
  410. import AIWorkModal from './components/AIWorkModal.vue'
  411. import DialoguePanel from './components/DialoguePanel.vue'
  412. import ChoiceStatistics from './components/ChoiceStatistics.vue'
  413. import * as Y from 'yjs'
  414. import { WebsocketProvider } from 'y-websocket'
  415. import { Refresh } from '@icon-park/vue-next'
  416. import answerTheResult from './components/answerTheResult.vue'
  417. import choiceQuestionDetailDialog from './components/choiceQuestionDetailDialog.vue'
  418. import SpeakingClassPanel from './components/SpeakingClassPanel/index.vue'
  419. import ArticleReadingClassPanel from './components/ArticleReadingClassPanel/index.vue'
  420. import {
  421. ARTICLE_READING_TOOL_TYPE,
  422. TOPIC_DISCUSSION_TOOL_TYPE,
  423. isArticleReadingTool,
  424. isTopicDiscussionTool,
  425. } from '@/configs/englishSpeakingTools'
  426. import aiChat from './components/aiChat.vue'
  427. import messageInstruction from '@/utils/components/messageInstruction.vue'
  428. const messageInstructionRef = ref<typeof messageInstruction>()
  429. // 生成标准 UUID v4 格式(36位,符合 [0-9a-fA-F-] 格式)
  430. const generateUUID = (): string => {
  431. // 优先使用浏览器原生 API
  432. if (typeof crypto !== 'undefined' && crypto.randomUUID) {
  433. return crypto.randomUUID()
  434. }
  435. // 降级方案:手动生成 UUID v4
  436. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
  437. const r = (Math.random() * 16) | 0
  438. const v = c === 'x' ? r : (r & 0x3) | 0x8
  439. return v.toString(16)
  440. })
  441. }
  442. // 导入图片资源
  443. import homeworkIcon from '@/assets/img/homework.png'
  444. import homeworkActiveIcon from '@/assets/img/homework-active.png'
  445. import dialogueIcon from '@/assets/img/dialogue.png'
  446. import dialogueActiveIcon from '@/assets/img/dialogue-active.png'
  447. import choiceIcon from '@/assets/img/choice.png'
  448. import choiceActiveIcon from '@/assets/img/choice-active.png'
  449. // 定义组件props
  450. interface Props {
  451. courseid?: string | null
  452. userid?: string | null
  453. oid?: string | null
  454. org?: string | null
  455. cid?: string | null
  456. type?: string | null
  457. }
  458. const props = withDefaults(defineProps<Props>(), {
  459. courseid: null,
  460. userid: null,
  461. oid: null,
  462. org: null,
  463. cid: null,
  464. type: null,
  465. })
  466. // 图标组件通过全局注册,无需导入
  467. const slidesStore = useSlidesStore()
  468. const { slides, slideIndex, currentSlide, viewportSize, viewportRatio } = storeToRefs(slidesStore)
  469. // 添加容器引用,用于计算幻灯片尺寸
  470. const viewerCanvasRef = ref<HTMLElement>()
  471. // 放映相关的状态
  472. const canvasScale = ref(1) // 画布缩放比例
  473. const isFullscreen = ref(false) // 是否全屏
  474. const hwBoxExpanded = ref(false) // 全屏下作业工具栏展开状态
  475. const containerWidth = ref(0) // 容器宽度
  476. const containerHeight = ref(0) // 容器高度
  477. // 全屏工具相关状态
  478. const rightToolsVisible = ref(false)
  479. const writingBoardToolVisible = ref(false)
  480. const timerlVisible = ref(false)
  481. const slideThumbnailModelVisible = ref(false)
  482. const laserPen = ref(false)
  483. // 学生端激光笔覆盖层与位置(百分比)
  484. const laserPenOverlay = ref<{ visible: boolean; xPct: number; yPct: number }>({ visible: false, xPct: 0, yPct: 0 })
  485. const laserDotRef = ref<HTMLElement | null>(null)
  486. let laserMoveRafId: number | null = null
  487. let lastLayout: { w: number; h: number } | null = null
  488. // 学生端覆盖层矩形(固定定位)
  489. const laserOverlayRect = ref<{ left: number; top: number; width: number; height: number }>({ left: 0, top: 0, width: 0, height: 0 })
  490. const laserOverlayStyle = computed(() => ({
  491. position: 'fixed' as const,
  492. left: laserOverlayRect.value.left + 'px',
  493. top: laserOverlayRect.value.top + 'px',
  494. width: laserOverlayRect.value.width + 'px',
  495. height: laserOverlayRect.value.height + 'px',
  496. pointerEvents: 'auto' as const,
  497. zIndex: 1000
  498. }))
  499. const refreshLaserOverlayRect = () => {
  500. const wrap = (viewerCanvasRef.value?.querySelector('.slide-list-wrap') as HTMLElement) || null
  501. if (!wrap) return
  502. const rect = wrap.getBoundingClientRect()
  503. laserOverlayRect.value = { left: rect.left, top: rect.top, width: rect.width, height: rect.height }
  504. }
  505. const updateLaserDotPosition = () => {
  506. if (!laserDotRef.value || !viewerCanvasRef.value) return
  507. const wrap = (viewerCanvasRef.value.querySelector('.slide-list-wrap') as HTMLElement) || viewerCanvasRef.value
  508. const w = wrap.clientWidth
  509. const h = wrap.clientHeight
  510. lastLayout = { w, h }
  511. const left = (laserPenOverlay.value.xPct / 100) * w
  512. const top = (laserPenOverlay.value.yPct / 100) * h
  513. // 减去半径使光点中心对齐
  514. laserDotRef.value.style.transform = `translate3d(${left - 12}px, ${top - 12}px, 0)`
  515. }
  516. const answerTheResultRef = ref(null)
  517. // 计时状态指示器
  518. const timerIndicator = ref<{ visible: boolean; isCountdown: boolean; startAt: string | null; durationSec: number | null; elapsedSec: number | null; remainingSec: number | null; finished: boolean }>({
  519. visible: false,
  520. isCountdown: false,
  521. startAt: null,
  522. durationSec: null,
  523. elapsedSec: null,
  524. remainingSec: null,
  525. finished: false,
  526. })
  527. const timerInterval = ref<number | null>(null)
  528. // 作业提交状态
  529. const isSubmitting = ref(false)
  530. // 进入当前幻灯片(作业页)的时间戳,用于计算作业提交耗时(秒)
  531. const slideEnterTime = ref(0)
  532. // 控制组件显示的开关
  533. const showSlideList = ref(true)
  534. const slideWidth = ref(0)
  535. const slideHeight = ref(0)
  536. const slideWidth2 = ref(0)
  537. const slideHeight2 = ref(0)
  538. // 添加loading状态
  539. const isLoading = ref(false)
  540. const workLoading = ref(false)
  541. const studentLoading = ref(false)
  542. // 作业数组
  543. type WorkItem = {
  544. id?: string | number
  545. name: string
  546. type: number | string
  547. [key: string]: any
  548. }
  549. const workArray = ref<WorkItem[]>([])
  550. const toolTypeArray = ref<number[]>([45, 15, 73, 72, 78, 79, 831, 832, 84])
  551. // 作业弹窗相关
  552. const selectedWork = ref<any>(null)
  553. const visibleShot = ref(false)
  554. const visibleQA = ref(false)
  555. const visibleChoice = ref(false)
  556. const visibleAI = ref(false)
  557. const choiceQuestionDetailDialogOpenList = ref<number[]>([])
  558. const speakingPanelRef = ref<InstanceType<typeof SpeakingClassPanel> | null>(null)
  559. const articleReadingPanelRef = ref<InstanceType<typeof ArticleReadingClassPanel> | null>(null)
  560. const choiceQuestionDetailDialogRef = ref<InstanceType<typeof choiceQuestionDetailDialog> | null>(null)
  561. provide('notifySpeakingProgress', (status: 'active' | 'completed', payload: { configId: string; sessionId: string }) => {
  562. if (props.type !== '2') return // 只有学生客户端发广播
  563. sendMessage({
  564. type: 'speaking_session_updated',
  565. courseid: props.courseid,
  566. slideIndex: slideIndex.value,
  567. userid: props.userid,
  568. status,
  569. ...payload,
  570. })
  571. })
  572. provide('recordSpeakingStart', async (
  573. sessionId: string,
  574. activityToolType: number = TOPIC_DISCUSSION_TOOL_TYPE,
  575. ) => {
  576. // 老师端 (type=1) 与学生端 (type=2) 都允许写作业记录,方便老师自测/学生提交
  577. if (!sessionId || !props.courseid || !props.userid) return
  578. try {
  579. await api.submitWork({
  580. uid: props.userid as string,
  581. cid: props.courseid as string,
  582. stage: '0',
  583. task: String(slideIndex.value),
  584. tool: '0',
  585. atool: String(activityToolType),
  586. content: sessionId,
  587. type: '21',
  588. })
  589. }
  590. catch (err) {
  591. console.error('[speaking] recordSpeakingStart failed:', err)
  592. }
  593. })
  594. // 提供给子组件使用
  595. provide('choiceQuestionDetailDialogOpenList', choiceQuestionDetailDialogOpenList)
  596. // 当前作业选择/问答题的ID
  597. const workId = ref<string>('')
  598. // 当前作业的url
  599. const workUrl = ref<string>('')
  600. // 当前作业的type
  601. const toolType = ref<string>('')
  602. // 回答结果收缩状态
  603. const workPanelCollapsed = ref(true)
  604. // 幻灯片导航收缩状态
  605. const slidePanelCollapsed = ref(true)
  606. // 右侧面板当前显示的内容:'homework' | 'dialogue' | 'choice'
  607. const rightPanelMode = ref<'homework' | 'dialogue' | 'choice' | ''>('homework')
  608. // 移除定时器相关代码,改用socket监听
  609. const courseDetail = ref<any>({})
  610. const aiAssistant = ref<boolean>(false)
  611. const studentArray = ref<any>([])
  612. const isResultArray = ref<any>([])
  613. const opRes = ref<any>([])
  614. // 跟随模式相关状态
  615. const isCreator = ref(false) // 是否为创建人
  616. const isFollowModeActive = ref(false) // 跟随模式是否开启
  617. const isFirstEnter = ref(true) // 是否首次进入
  618. // 用户信息
  619. const userJson = ref<any>(null)
  620. // 计算未提交作业的学生
  621. const unsubmittedStudents = computed(() => {
  622. if (!studentArray.value || !workArray.value) return []
  623. // 获取已提交作业的学生姓名
  624. const submittedNames = workArray.value.map(work => work.name)
  625. // 过滤出未提交作业的学生
  626. return studentArray.value.filter((student: any) => !submittedNames.includes(student.name))
  627. })
  628. const docSocket = ref<Y.Doc | null>(null)
  629. const yMessage = ref<any | null>(null)
  630. const yTimerState = ref<any | null>(null)
  631. const yLaserState = ref<any | null>(null)
  632. const yWritingBoardState = ref<any | null>(null)
  633. // 独立的数组存储特殊类型的消息
  634. const yTimerMessages = ref<any | null>(null)
  635. const yLaserMessages = ref<any | null>(null)
  636. const yWritingBoardMessages = ref<any | null>(null)
  637. const yIsResultArrayMessages = ref<any | null>(null)
  638. const providerSocket = ref<WebsocketProvider | null>(null)
  639. // 学生端画图同步数据
  640. const writingBoardSyncDataURL = ref<string | null>(null)
  641. const writingBoardSyncBlackboard = ref<boolean | null>(null)
  642. const mId = ref<string | null>(null)
  643. // 画图延迟发送定时器
  644. const drawingDelayTimer = ref<NodeJS.Timeout | null>(null)
  645. // WebSocket重连相关变量
  646. const reconnectAttempts = ref(0)
  647. const maxReconnectAttempts = ref(5) // 最大重连次数
  648. const reconnectInterval = ref(5000) // 重连间隔(毫秒)
  649. const reconnectTimer = ref<NodeJS.Timeout | null>(null)
  650. const isConnecting = ref(false)
  651. const connectionStatus = ref<'disconnected' | 'connecting' | 'connected'>('disconnected')
  652. // 认证 token 相关变量
  653. const authToken = ref<string | null>(null)
  654. const authTokenUpdateTimer = ref<NodeJS.Timeout | null>(null)
  655. const heartbeatTimer = ref<NodeJS.Timeout | null>(null)
  656. const socketCheckTimer = ref<NodeJS.Timeout | null>(null)
  657. // 同步数据最大保留时间(40分钟)
  658. const SYNC_DATA_MAX_AGE = 40 * 60 * 1000 // 40分钟 = 40 * 60 * 1000毫秒
  659. // 切换选择题题目
  660. const changeWorkIndex = (type:number) => {
  661. if (answerTheResultRef.value && answerTheResultRef.value.changeWorkIndex) {
  662. answerTheResultRef.value.changeWorkIndex(type)
  663. }
  664. }
  665. // 切换到回答结果
  666. const switchToHomework = () => {
  667. rightPanelMode.value = 'homework'
  668. if (workPanelCollapsed.value) {
  669. workPanelCollapsed.value = false
  670. }
  671. }
  672. // 切换到对话区
  673. const switchToDialogue = () => {
  674. rightPanelMode.value = 'dialogue'
  675. if (workPanelCollapsed.value) {
  676. workPanelCollapsed.value = false
  677. }
  678. }
  679. // 切换到选择题统计
  680. const switchToChoice = () => {
  681. rightPanelMode.value = 'choice'
  682. if (workPanelCollapsed.value) {
  683. workPanelCollapsed.value = false
  684. }
  685. }
  686. // 自动切换到可用的面板
  687. const autoSwitchToAvailablePanel = () => {
  688. // 如果当前在回答结果但没有iframe,自动切换到其他可用面板
  689. if (rightPanelMode.value === 'homework' && !currentSlideHasIframe.value && !currentSlideHasBilibiliVideo.value) {
  690. if (isChoiceQuestion.value) {
  691. rightPanelMode.value = 'choice'
  692. console.log('自动切换到统计面板')
  693. }
  694. else {
  695. rightPanelMode.value = 'dialogue'
  696. console.log('自动切换到对话面板')
  697. }
  698. }
  699. // 如果当前在统计面板但不是选择题,自动切换到对话面板
  700. else if (rightPanelMode.value === 'choice' && !isChoiceQuestion.value) {
  701. rightPanelMode.value = 'dialogue'
  702. console.log('自动切换到对话面板')
  703. }
  704. // else if (currentSlideHasIframe.value && rightPanelMode.value !== 'homework' && !currentSlideHasBilibiliVideo.value) {
  705. // rightPanelMode.value = 'homework'
  706. // }
  707. }
  708. // 移除定时器相关函数,改用socket监听
  709. // 收缩/展开后重新计算中间画布尺寸(在 DOM 更新并完成过渡后)
  710. watch([() => workPanelCollapsed.value, () => slidePanelCollapsed.value], async () => {
  711. // 等待本次 DOM 更新
  712. await nextTick()
  713. // 先在下一帧计算一次,确保初步布局就绪
  714. requestAnimationFrame(() => {
  715. calculateScale()
  716. })
  717. // 再在过渡结束后(与左右栏 width .2s 过渡一致)复算一次,确保最终尺寸
  718. setTimeout(() => {
  719. calculateScale()
  720. }, 220)
  721. }, { flush: 'post' })
  722. const openWorkModal = (work: WorkItem) => {
  723. selectedWork.value = work
  724. const t = Number(work?.type)
  725. // if (t !== 1) {
  726. // message.warning('暂未开发完成')
  727. // return
  728. // }
  729. visibleShot.value = false
  730. visibleQA.value = false
  731. visibleChoice.value = false
  732. visibleAI.value = false
  733. if (t === 1) {
  734. visibleShot.value = true
  735. }
  736. else if (t === 3) {
  737. visibleQA.value = true
  738. }
  739. else if (t === 8) {
  740. visibleChoice.value = true
  741. }
  742. else if (t === 20) {
  743. visibleAI.value = true
  744. }
  745. else {
  746. message.info(lang.ssHwTypeUnsup)
  747. }
  748. }
  749. // 计算幻灯片尺寸的函数
  750. const calculateSlideSize = () => {
  751. const slideWrapRef = isFullscreen.value ? document.body : viewerCanvasRef.value
  752. const winWidth = slideWrapRef?.clientWidth || 0
  753. const winHeight = slideWrapRef?.clientHeight || 0
  754. const winWidth2 = slideWrapRef && typeof slideWrapRef.clientWidth === 'number' ? slideWrapRef.clientWidth - 40 : 0
  755. const winHeight2 = slideWrapRef && typeof slideWrapRef.clientHeight === 'number' ? slideWrapRef.clientHeight - 60 - 65 - 10 : 0 // 底部栏 顶部高度 底部高度的
  756. // 根据视口比例计算最佳尺寸
  757. if (winHeight / winWidth === viewportRatio.value) {
  758. slideWidth.value = winWidth
  759. slideHeight.value = winHeight
  760. }
  761. else if (winHeight / winWidth > viewportRatio.value) {
  762. slideWidth.value = winWidth
  763. slideHeight.value = winWidth * viewportRatio.value
  764. }
  765. else {
  766. slideWidth.value = winHeight / viewportRatio.value
  767. slideHeight.value = winHeight
  768. }
  769. // 这里的逻辑存在一些问题和可以优化的地方:
  770. // 1. winWidth2 或 winHeight2 可能为0,导致后续计算为NaN。
  771. // 2. slideHeight.value - slideHeight2.value < 85 这个判断,slideHeight2.value 可能还未被合理赋值,导致判断不准确。
  772. // 3. 反复赋值 slideHeight2/slideWidth2,可能导致宽高比被破坏。
  773. // 4. 代码重复,可合并优化。
  774. // 先按比例计算
  775. let tempWidth = 0
  776. let tempHeight = 0
  777. if (winHeight2 / winWidth2 === viewportRatio.value) {
  778. tempWidth = winWidth2
  779. tempHeight = winHeight2
  780. }
  781. else if (winHeight2 / winWidth2 > viewportRatio.value) {
  782. tempWidth = winWidth2
  783. tempHeight = winWidth2 * viewportRatio.value
  784. }
  785. else {
  786. tempHeight = winHeight2
  787. tempWidth = winHeight2 / viewportRatio.value
  788. }
  789. // 检查底部空间
  790. if (slideHeight.value - tempHeight < (60 + 65 + 10)) {
  791. tempHeight = Math.max(slideHeight.value - (60 + 65 + 10), 0)
  792. tempWidth = tempHeight > 0 ? tempHeight / viewportRatio.value : 0
  793. }
  794. slideWidth2.value = tempWidth
  795. slideHeight2.value = tempHeight
  796. console.log('calculateSlideSize', slideWidth.value, slideHeight.value, viewportRatio.value, canvasScale.value)
  797. console.log('calculateSlideSize', slideWidth2.value, slideHeight2.value, viewportRatio.value, canvasScale.value)
  798. }
  799. // 使用编辑模式的缩放逻辑
  800. const calculateScale = () => {
  801. console.log('calculateScale 开始执行')
  802. // 获取容器尺寸
  803. const container = viewerCanvasRef.value || document.querySelector('.viewer-canvas')
  804. if (container) {
  805. containerWidth.value = container.clientWidth
  806. containerHeight.value = container.clientHeight
  807. console.log('容器尺寸:', {
  808. width: containerWidth.value,
  809. height: containerHeight.value
  810. })
  811. // 计算基础尺寸
  812. const baseWidth = viewportSize.value
  813. const baseHeight = viewportSize.value * viewportRatio.value
  814. console.log('基础尺寸:', {
  815. baseWidth,
  816. baseHeight,
  817. viewportSize: viewportSize.value,
  818. viewportRatio: viewportRatio.value
  819. })
  820. // 计算缩放比例,让幻灯片能够合理利用空间
  821. const scaleX = containerWidth.value / baseWidth
  822. const scaleY = containerHeight.value / baseHeight
  823. console.log('原始缩放比例:', { scaleX, scaleY })
  824. // 选择较小的缩放比例,确保幻灯片完全显示且居中,留10%边距
  825. const scale = Math.min(scaleX, scaleY) * 0.9
  826. console.log('最终缩放比例:', scale)
  827. canvasScale.value = isFullscreen.value ? 1 : props.type == '1' ? 1 : 1
  828. // canvasScale.value = 1
  829. }
  830. else {
  831. console.error('找不到容器元素')
  832. }
  833. // 计算幻灯片尺寸
  834. nextTick(() => {
  835. setTimeout(() => {
  836. calculateSlideSize()
  837. if (laserPenOverlay.value.visible) {
  838. refreshLaserOverlayRect()
  839. requestAnimationFrame(updateLaserDotPosition)
  840. }
  841. }, 500)
  842. })
  843. }
  844. // 简化:直接使用放映功能的缩放逻辑
  845. const resetZoom = () => {
  846. calculateScale()
  847. }
  848. // 背景样式
  849. const background = computed(() => currentSlide.value?.background)
  850. const { backgroundStyle } = useSlideBackgroundStyle(background)
  851. // 计算当前幻灯片的元素列表
  852. const elementList = computed(() => {
  853. return currentSlide.value?.elements || []
  854. })
  855. // 检查当前是否为选择题(toolType为45)
  856. const isChoiceQuestion = computed(() => {
  857. const frame = elementList.value.find(element => element.type === ElementTypes.FRAME)
  858. return frame?.toolType === 45
  859. })
  860. const isQuestionFrame = computed(() => {
  861. const frame = elementList.value.find(element => element.type === ElementTypes.FRAME)
  862. return frame?.toolType === 45 || frame?.toolType === 15 || frame?.toolType === 78
  863. })
  864. const hasWork = computed(() => {
  865. return workArray.value.find(work => work.userid === props.userid) !== undefined
  866. })
  867. const myWork = computed(() => {
  868. return workArray.value.find(work => work.userid === props.userid)
  869. })
  870. // AI按钮拖动相关状态
  871. const aiBtnPosition = ref({ x: 80, y: 70 }) // 初始位置(从右下角计算)
  872. const isDragging = ref(false)
  873. const dragStart = ref({ x: 0, y: 0 })
  874. const slideListWrapRef = ref<HTMLElement | null>(null)
  875. const aiBtnRef = ref<HTMLElement | null>(null)
  876. // 处理AI按钮开始拖动
  877. const handleAiBtnPointerDown = (e: PointerEvent) => {
  878. isDragging.value = true
  879. const aiBtn = aiBtnRef.value
  880. if (aiBtn) {
  881. // 设置指针捕获,确保即使鼠标移出元素也能继续接收事件
  882. aiBtn.setPointerCapture(e.pointerId)
  883. }
  884. // 获取slide-list-wrap元素的位置和尺寸
  885. const slideListWrap = slideListWrapRef.value
  886. if (slideListWrap) {
  887. const rect = slideListWrap.getBoundingClientRect()
  888. dragStart.value = {
  889. x: e.clientX - (rect.right - aiBtnPosition.value.x),
  890. y: e.clientY - (rect.bottom - aiBtnPosition.value.y)
  891. }
  892. }
  893. e.preventDefault()
  894. }
  895. // 处理拖动中
  896. const handleAiBtnPointerMove = (e: PointerEvent) => {
  897. if (isDragging.value) {
  898. const slideListWrap = slideListWrapRef.value
  899. if (slideListWrap) {
  900. const rect = slideListWrap.getBoundingClientRect()
  901. // 计算新位置(从slide-list-wrap右下角计算)
  902. const newX = rect.right - (e.clientX - dragStart.value.x)
  903. const newY = rect.bottom - (e.clientY - dragStart.value.y)
  904. // 限制在slide-list-wrap范围内
  905. const aiBtnWidth = 120 // 估计AI按钮宽度
  906. const aiBtnHeight = 40 // 估计AI按钮高度
  907. aiBtnPosition.value = {
  908. x: Math.max(20, Math.min(newX, rect.width - aiBtnWidth)),
  909. y: Math.max(20, Math.min(newY, rect.height - aiBtnHeight))
  910. }
  911. }
  912. }
  913. }
  914. // 处理拖动结束
  915. const handleAiBtnPointerUp = (e: PointerEvent) => {
  916. isDragging.value = false
  917. const aiBtn = aiBtnRef.value
  918. if (aiBtn) {
  919. // 释放指针捕获
  920. aiBtn.releasePointerCapture(e.pointerId)
  921. }
  922. }
  923. // 处理指针取消(如浏览器标签页切换)
  924. const handleAiBtnPointerCancel = (e: PointerEvent) => {
  925. isDragging.value = false
  926. const aiBtn = aiBtnRef.value
  927. if (aiBtn) {
  928. // 释放指针捕获
  929. aiBtn.releasePointerCapture(e.pointerId)
  930. }
  931. }
  932. // 监听isQuestionFrame和hasWork的变化,当按钮显示时添加事件监听器
  933. watch([isQuestionFrame, hasWork], ([newIsQuestionFrame, newHasWork]) => {
  934. if (newIsQuestionFrame && newHasWork) {
  935. // 按钮显示了,添加事件监听器
  936. nextTick(() => {
  937. const aiBtn = aiBtnRef.value
  938. if (aiBtn) {
  939. aiBtn.addEventListener('pointerdown', handleAiBtnPointerDown)
  940. aiBtn.addEventListener('pointermove', handleAiBtnPointerMove)
  941. aiBtn.addEventListener('pointerup', handleAiBtnPointerUp)
  942. aiBtn.addEventListener('pointercancel', handleAiBtnPointerCancel)
  943. }
  944. })
  945. }
  946. else {
  947. // 按钮隐藏了,移除事件监听器
  948. const aiBtn = aiBtnRef.value
  949. if (aiBtn) {
  950. aiBtn.removeEventListener('pointerdown', handleAiBtnPointerDown)
  951. aiBtn.removeEventListener('pointermove', handleAiBtnPointerMove)
  952. aiBtn.removeEventListener('pointerup', handleAiBtnPointerUp)
  953. aiBtn.removeEventListener('pointercancel', handleAiBtnPointerCancel)
  954. }
  955. }
  956. })
  957. onUnmounted(() => {
  958. // 移除事件监听器
  959. const aiBtn = aiBtnRef.value
  960. if (aiBtn) {
  961. aiBtn.removeEventListener('pointerdown', handleAiBtnPointerDown)
  962. aiBtn.removeEventListener('pointermove', handleAiBtnPointerMove)
  963. aiBtn.removeEventListener('pointerup', handleAiBtnPointerUp)
  964. aiBtn.removeEventListener('pointercancel', handleAiBtnPointerCancel)
  965. }
  966. cleanupWebSocketConnection()
  967. })
  968. const visibleAIChat = ref(false)
  969. // 打开AI对话框
  970. const openAiChat = () => {
  971. visibleAIChat.value = !visibleAIChat.value
  972. }
  973. // 检测当前幻灯片是否包含iframe元素
  974. const currentSlideHasIframe = computed(() => {
  975. console.log('elementList.value', elementList.value)
  976. return elementList.value.some(element => element.type === ElementTypes.FRAME)
  977. })
  978. const currentSlideToolType = computed(() => {
  979. const frame = elementList.value.find(element => element.type === ElementTypes.FRAME)
  980. return Number((frame as any)?.toolType) || 0
  981. })
  982. const currentSlideConfigId = computed(() => {
  983. const toolType = currentSlideToolType.value
  984. if (!isTopicDiscussionTool(toolType) && !isArticleReadingTool(toolType)) return ''
  985. const frame = elementList.value.find(element => element.type === ElementTypes.FRAME)
  986. return (frame as any)?.url || ''
  987. })
  988. // 检测当前幻灯片是否包含B站视频
  989. const currentSlideHasBilibiliVideo = computed(() => {
  990. return elementList.value.some(element =>
  991. element.type === ElementTypes.FRAME && (element.toolType === 75 || element.toolType === 74 || element.toolType === 76 || element.toolType === 81)
  992. )
  993. })
  994. // 检测当前幻灯片是否是英语口语(话题讨论或文章朗读):
  995. // 通用作业提交/刷新按钮对这两类都必须保持抑制
  996. const currentSlideHasEnglishSpeaking = computed(() => {
  997. return elementList.value.some(element =>
  998. element.type === ElementTypes.FRAME &&
  999. (isTopicDiscussionTool(element.toolType) || isArticleReadingTool(element.toolType))
  1000. )
  1001. })
  1002. // 检查当前的结果状态
  1003. const currentIsResultArray = computed(() => {
  1004. console.log('isResultArray.value[slideIndex.value]', isResultArray.value[slideIndex.value])
  1005. return isResultArray.value[slideIndex.value] || {}
  1006. })
  1007. // 跳转到指定幻灯片
  1008. const goToSlide = (index: number) => {
  1009. console.log('goToSlide 被调用,目标索引:', index)
  1010. console.log('当前索引:', slideIndex.value, 'slides长度:', slides.value.length)
  1011. // slides 还没加载完时,暂存目标索引,等 slides 就绪后再跳转
  1012. if (slides.value.length === 0) {
  1013. console.warn('goToSlide: slides 未加载,暂存目标索引:', index)
  1014. pendingSlideIndex.value = index
  1015. return
  1016. }
  1017. if (index >= 0 && index < slides.value.length) {
  1018. slidesStore.updateSlideIndex(index)
  1019. console.log('更新后的索引:', slideIndex.value)
  1020. }
  1021. else {
  1022. console.warn('goToSlide: 无效的索引:', index)
  1023. }
  1024. }
  1025. // 暂存的目标幻灯片索引(slides 未就绪时使用)
  1026. const pendingSlideIndex = ref<number | null>(null)
  1027. // slides 加载完成后应用暂存的跳转
  1028. watch(() => slides.value.length, (len) => {
  1029. if (len > 0 && pendingSlideIndex.value !== null) {
  1030. const idx = pendingSlideIndex.value
  1031. pendingSlideIndex.value = null
  1032. if (idx >= 0 && idx < len) {
  1033. console.log('🔄 slides 就绪,应用暂存的跳转索引:', idx)
  1034. slidesStore.updateSlideIndex(idx)
  1035. }
  1036. }
  1037. })
  1038. // 上一页
  1039. const previousSlide = () => {
  1040. if (slideIndex.value > 0) {
  1041. const newIndex = slideIndex.value - 1
  1042. console.log('上一页,从', slideIndex.value, '到', newIndex)
  1043. slidesStore.updateSlideIndex(newIndex)
  1044. }
  1045. }
  1046. // 下一页
  1047. const nextSlide = () => {
  1048. if (slideIndex.value < slides.value.length - 1) {
  1049. const newIndex = slideIndex.value + 1
  1050. console.log('下一页,从', slideIndex.value, '到', newIndex)
  1051. slidesStore.updateSlideIndex(newIndex)
  1052. }
  1053. }
  1054. // 监听幻灯片切换,清除不匹配的画图数据
  1055. watch(() => slideIndex.value, () => {
  1056. if (props.type == '2' && yWritingBoardState.value && currentSlide.value) {
  1057. const snap = yWritingBoardState.value.toJSON()
  1058. console.log('📝 幻灯片切换,检查画图数据:', { snap, currentSlideId: currentSlide.value.id })
  1059. if (snap && snap.slideId === currentSlide.value.id && snap.dataURL) {
  1060. // 当前幻灯片有画图数据,显示
  1061. writingBoardSyncDataURL.value = snap.dataURL
  1062. writingBoardSyncBlackboard.value = snap.blackboard !== undefined ? snap.blackboard : null
  1063. console.log('📝 当前幻灯片有画图数据,显示画图工具,小黑板状态:', writingBoardSyncBlackboard.value)
  1064. }
  1065. else {
  1066. // 当前幻灯片没有画图数据,隐藏
  1067. writingBoardSyncDataURL.value = null
  1068. writingBoardSyncBlackboard.value = null
  1069. console.log('📝 当前幻灯片没有画图数据,隐藏画图工具')
  1070. }
  1071. if (visibleAIChat.value) {
  1072. visibleAIChat.value = false
  1073. }
  1074. }
  1075. })
  1076. // 监听 currentSlide 变化,确保刷新后能获取到画图状态
  1077. watch(() => currentSlide.value?.id, (newSlideId, oldSlideId) => {
  1078. // 记录进入当前幻灯片的时间戳(immediate 保证刷新后 slides 加载完成也能记录)
  1079. if (newSlideId && newSlideId !== oldSlideId) {
  1080. slideEnterTime.value = Date.now()
  1081. }
  1082. // 只在学生端且跟随模式下检查
  1083. if (props.type == '2' && isFollowModeActive.value && yWritingBoardState.value && newSlideId) {
  1084. const snap = yWritingBoardState.value.toJSON()
  1085. console.log('📝 currentSlide变化,检查画图数据:', { snap, newSlideId, oldSlideId })
  1086. if (snap && snap.slideId === newSlideId && snap.dataURL) {
  1087. // 当前幻灯片有画图数据,显示
  1088. writingBoardSyncDataURL.value = snap.dataURL
  1089. writingBoardSyncBlackboard.value = snap.blackboard !== undefined ? snap.blackboard : null
  1090. console.log('📝 currentSlide变化后找到画图数据,显示画图工具,小黑板状态:', writingBoardSyncBlackboard.value)
  1091. }
  1092. else if (snap && snap.slideId !== newSlideId) {
  1093. // 当前幻灯片没有画图数据,隐藏
  1094. writingBoardSyncDataURL.value = null
  1095. writingBoardSyncBlackboard.value = null
  1096. console.log('📝 currentSlide变化后没有匹配的画图数据,隐藏画图工具')
  1097. }
  1098. }
  1099. }, { immediate: true })
  1100. // 监听slideIndex变化,调用getWork
  1101. watch(() => slideIndex.value, (newIndex, oldIndex) => {
  1102. console.log('slideIndex变化,调用getWork', { newIndex, oldIndex })
  1103. if (newIndex !== oldIndex && typeof newIndex === 'number') {
  1104. // 检查新页面是否有iframe
  1105. const hasIframe = currentSlideHasIframe.value
  1106. if (hasIframe) {
  1107. console.log('当前页面有iframe,获取作业数据')
  1108. console.log('触发getWork,当前幻灯片索引:', newIndex)
  1109. getWork()
  1110. }
  1111. if (props.type == '1' && isFollowModeActive.value && isCreator.value) {
  1112. api.updateCourseFollowC(newIndex, props.courseid as string)
  1113. sendMessage({slideIndex: newIndex, courseid: props.courseid, type: 'slideIndex'})
  1114. }
  1115. // 自动切换到可用的面板
  1116. autoSwitchToAvailablePanel()
  1117. if (isSubmitting.value) {
  1118. isSubmitting.value = false
  1119. }
  1120. if (timerlVisible.value) {
  1121. timerlVisible.value = false
  1122. }
  1123. }
  1124. getWorkId()
  1125. }, { immediate: false, deep: false })
  1126. // 监听iframe状态变化,自动切换面板
  1127. watch(() => currentSlideHasIframe.value, (hasIframe) => {
  1128. if (!hasIframe) {
  1129. autoSwitchToAvailablePanel()
  1130. }
  1131. }, { immediate: false })
  1132. // 全屏
  1133. const enterFullscreen = () => {
  1134. if (document.fullscreenElement) {
  1135. document.exitFullscreen()
  1136. }
  1137. else {
  1138. document.documentElement.requestFullscreen()
  1139. }
  1140. }
  1141. // 监听全屏状态变化
  1142. const handleFullscreenChange = () => {
  1143. isFullscreen.value = !!document.fullscreenElement
  1144. if (isFullscreen.value) {
  1145. // 全屏时不需要计算缩放,直接使用放映功能
  1146. console.log('进入全屏模式')
  1147. }
  1148. else {
  1149. // 退出全屏时重置所有工具状态并重新计算缩放比例
  1150. console.log('退出全屏模式,重置工具状态')
  1151. // 重置所有工具状态
  1152. rightToolsVisible.value = false
  1153. writingBoardToolVisible.value = false
  1154. slideThumbnailModelVisible.value = false
  1155. laserPen.value = false
  1156. // 重新计算缩放比例
  1157. nextTick(() => {
  1158. setTimeout(() => {
  1159. calculateScale()
  1160. }, 1000)
  1161. })
  1162. }
  1163. }
  1164. const getWorkId = () => {
  1165. // 修复类型报错:elementList 可能没有 toolType 和 url 字段,需先判断类型
  1166. const element = elementList.value.find((i:any) => i.type === 'frame')
  1167. console.log(element)
  1168. if (
  1169. element &&
  1170. typeof element === 'object' &&
  1171. ('toolType' in element) &&
  1172. (element as any).toolType !== undefined &&
  1173. toolTypeArray.value.includes((element as any).toolType)
  1174. ) {
  1175. // 提取链接中的id参数
  1176. const url = (element as any).url
  1177. let id = ''
  1178. toolType.value = (element as any).toolType
  1179. if (typeof url === 'string') {
  1180. const match = url.match(/[?&]id=([^&]+)/)
  1181. if (match) {
  1182. id = match[1]
  1183. }
  1184. workUrl.value = url
  1185. workId.value = id
  1186. if ((element as any).toolType === 72) {
  1187. workId.value = (element as any).id
  1188. }
  1189. }
  1190. else {
  1191. workId.value = ''
  1192. workUrl.value = ''
  1193. }
  1194. }
  1195. else {
  1196. workId.value = ''
  1197. workUrl.value = ''
  1198. }
  1199. }
  1200. // 处理画图关闭事件
  1201. const handleWritingBoardClose = () => {
  1202. // 学生端只读模式下,不应该响应关闭事件(因为关闭按钮已隐藏)
  1203. // 只有老师端可以关闭
  1204. if (props.type == '2') {
  1205. console.log('📝 学生端收到关闭事件,但只读模式下不应该关闭,忽略')
  1206. return
  1207. }
  1208. writingBoardToolVisible.value = false
  1209. // 老师端关闭时,清空共享状态并通知学生端
  1210. if (props.type == '1' && isFollowModeActive.value && isCreator.value) {
  1211. clearWritingBoardState()
  1212. }
  1213. }
  1214. // 清空画图共享状态(仅创建人)
  1215. const clearWritingBoardState = () => {
  1216. try {
  1217. if (props.type == '1' && isCreator.value && yWritingBoardState.value) {
  1218. docSocket.value?.transact(() => {
  1219. yWritingBoardState.value.clear()
  1220. })
  1221. sendMessage({
  1222. type: 'writing_board_close',
  1223. courseid: props.courseid
  1224. })
  1225. }
  1226. }
  1227. catch (e) {
  1228. console.warn('清空画图状态失败', e)
  1229. }
  1230. }
  1231. // 处理小黑板状态变化(老师端)
  1232. const handleBlackboardChange = (blackboard: boolean) => {
  1233. if (props.type == '1' && isFollowModeActive.value && isCreator.value) {
  1234. // 同步到共享 Map
  1235. if (yWritingBoardState.value) {
  1236. docSocket.value?.transact(() => {
  1237. yWritingBoardState.value.set('blackboard', blackboard)
  1238. })
  1239. }
  1240. // 广播消息
  1241. sendMessage({
  1242. type: 'writing_board_blackboard',
  1243. blackboard: blackboard,
  1244. courseid: props.courseid
  1245. })
  1246. }
  1247. }
  1248. // 处理画图结束事件(老师端)
  1249. const handleDrawingEnd = (dataURL: string) => {
  1250. if (props.type == '1' && isFollowModeActive.value && isCreator.value) {
  1251. // 同步到共享 Map
  1252. if (yWritingBoardState.value) {
  1253. docSocket.value?.transact(() => {
  1254. yWritingBoardState.value.set('slideId', currentSlide.value.id)
  1255. yWritingBoardState.value.set('dataURL', dataURL)
  1256. // 保持小黑板状态
  1257. const currentBlackboard = yWritingBoardState.value.get('blackboard')
  1258. if (currentBlackboard !== undefined) {
  1259. yWritingBoardState.value.set('blackboard', currentBlackboard)
  1260. }
  1261. })
  1262. }
  1263. // 延迟5秒后广播消息,避免频繁发送
  1264. if (drawingDelayTimer.value) {
  1265. clearTimeout(drawingDelayTimer.value)
  1266. }
  1267. drawingDelayTimer.value = setTimeout(() => {
  1268. const currentBlackboard = yWritingBoardState.value?.get('blackboard') || false
  1269. sendMessage({
  1270. type: 'writing_board_update',
  1271. slideId: currentSlide.value.id,
  1272. dataURL: dataURL,
  1273. blackboard: currentBlackboard,
  1274. courseid: props.courseid
  1275. })
  1276. drawingDelayTimer.value = null
  1277. }, 5000) // 延迟5秒发送
  1278. }
  1279. }
  1280. // 应用画图共享状态(任意端)
  1281. const applyWritingBoardStateSnapshot = (snap: any) => {
  1282. console.log('📝 应用画图状态快照:', snap, '当前幻灯片ID:', currentSlide.value?.id, '跟随模式:', isFollowModeActive.value, '用户类型:', props.type)
  1283. if (!snap || !snap.dataURL || typeof snap.dataURL !== 'string' || snap.dataURL.trim() === '') {
  1284. writingBoardSyncDataURL.value = null
  1285. writingBoardSyncBlackboard.value = null
  1286. console.log('📝 画图状态为空,隐藏画图工具')
  1287. return
  1288. }
  1289. const slideId = snap.slideId
  1290. const dataURL = snap.dataURL
  1291. const blackboardState = snap.blackboard !== undefined ? snap.blackboard : null
  1292. // 只有当前幻灯片匹配时才显示
  1293. if (slideId && currentSlide.value && slideId === currentSlide.value.id) {
  1294. writingBoardSyncDataURL.value = dataURL
  1295. writingBoardSyncBlackboard.value = blackboardState
  1296. console.log('📝 画图数据匹配,显示画图工具,数据长度:', dataURL.length, '小黑板状态:', blackboardState, '显示条件:', {
  1297. type: props.type,
  1298. isFollowModeActive: isFollowModeActive.value,
  1299. hasData: !!writingBoardSyncDataURL.value
  1300. })
  1301. }
  1302. else {
  1303. writingBoardSyncDataURL.value = null
  1304. writingBoardSyncBlackboard.value = null
  1305. console.log('📝 画图数据不匹配,隐藏画图工具', { slideId, currentSlideId: currentSlide.value?.id })
  1306. }
  1307. }
  1308. // 切换激光笔模式
  1309. const toggleLaserPen = () => {
  1310. laserPen.value = !laserPen.value
  1311. console.log('激光笔状态:', laserPen.value ? '开启' : '关闭')
  1312. // 老师端广播激光笔开关
  1313. if (props.type == '1') {
  1314. sendMessage({ type: 'laser_toggle', enabled: laserPen.value, courseid: props.courseid })
  1315. // 同步到共享 Map,方便后来者拿到状态
  1316. if (yLaserState.value) {
  1317. if (laserPen.value) {
  1318. const state: any = { enabled: true }
  1319. if (lastSent.x >= 0 && lastSent.y >= 0) {
  1320. state.x = lastSent.x; state.y = lastSent.y
  1321. }
  1322. docSocket.value?.transact(() => {
  1323. Object.entries(state).forEach(([k, v]) => yLaserState.value.set(k, v as any))
  1324. })
  1325. }
  1326. else {
  1327. // 关闭时清空共享状态
  1328. docSocket.value?.transact(() => {
  1329. yLaserState.value.clear()
  1330. })
  1331. }
  1332. }
  1333. }
  1334. }
  1335. // 老师端移动时广播激光笔位置(百分比坐标)
  1336. let sendRafPending = false
  1337. let lastSent = { x: -1, y: -1 }
  1338. const handleLaserMove = (e: MouseEvent) => {
  1339. if (!(props.type == '1' && laserPen.value)) return
  1340. // 始终以中间画布 .slide-list-wrap 为基准,避免外层左右留白导致的偏差
  1341. const wrap = (viewerCanvasRef.value?.querySelector('.slide-list-wrap') as HTMLElement) || (e.currentTarget as HTMLElement)
  1342. const rect = wrap.getBoundingClientRect()
  1343. const x = Math.min(Math.max(e.clientX - rect.left, 0), rect.width)
  1344. const y = Math.min(Math.max(e.clientY - rect.top, 0), rect.height)
  1345. const xPct = (x / rect.width) * 100
  1346. const yPct = (y / rect.height) * 100
  1347. // 小幅度移动忽略(阈值 0.4%)
  1348. if (Math.abs(xPct - lastSent.x) < 0.4 && Math.abs(yPct - lastSent.y) < 0.4) return
  1349. lastSent = { x: xPct, y: yPct }
  1350. if (sendRafPending) return
  1351. sendRafPending = true
  1352. requestAnimationFrame(() => {
  1353. sendRafPending = false
  1354. // sendMessage 中已经直接更新 Map,不需要重复更新
  1355. sendMessage({ type: 'laser_move', x: lastSent.x, y: lastSent.y, courseid: props.courseid })
  1356. })
  1357. }
  1358. // 清空激光笔共享状态(仅创建人)
  1359. const clearLaserState = () => {
  1360. try {
  1361. if (props.type == '1' && isCreator.value && yLaserState.value) {
  1362. docSocket.value?.transact(() => {
  1363. yLaserState.value.clear()
  1364. })
  1365. sendMessage({ type: 'laser_toggle', enabled: false, courseid: props.courseid })
  1366. }
  1367. }
  1368. catch (e) {
  1369. console.warn('清空激光笔状态失败', e)
  1370. }
  1371. }
  1372. // 清空所有同步状态(仅创建人)
  1373. const clearAllSyncStates = () => {
  1374. try {
  1375. if (props.type == '1' && isCreator.value && docSocket.value) {
  1376. console.log('🧹 创建老师退出,清空所有同步状态')
  1377. docSocket.value.transact(() => {
  1378. // ★ 不删除 latest!delete 会传播给学生导致 get('latest') 返回 undefined
  1379. // 旧 latest 会被 sendMessage 的 set('latest', message) 自然覆盖
  1380. const timerMessagesArray = docSocket.value?.getArray?.('timerMessages')
  1381. if (timerMessagesArray) {
  1382. timerMessagesArray.delete(0, timerMessagesArray.length)
  1383. }
  1384. // 清空激光笔消息数组
  1385. const laserMessagesArray = docSocket.value?.getArray?.('laserMessages')
  1386. if (laserMessagesArray) {
  1387. laserMessagesArray.delete(0, laserMessagesArray.length)
  1388. }
  1389. // 清空画图消息数组
  1390. const writingBoardMessagesArray = docSocket.value?.getArray?.('writingBoardMessages')
  1391. if (writingBoardMessagesArray) {
  1392. writingBoardMessagesArray.delete(0, writingBoardMessagesArray.length)
  1393. }
  1394. // 清空计时器状态
  1395. const timerStateMap = docSocket.value?.getMap?.('timerState')
  1396. if (timerStateMap) {
  1397. timerStateMap.clear()
  1398. }
  1399. // 清空激光笔状态
  1400. const laserStateMap = docSocket.value?.getMap?.('laserState')
  1401. if (laserStateMap) {
  1402. laserStateMap.clear()
  1403. }
  1404. // 清空画图状态
  1405. const writingBoardStateMap = docSocket.value?.getMap?.('writingBoardState')
  1406. if (writingBoardStateMap) {
  1407. writingBoardStateMap.clear()
  1408. }
  1409. })
  1410. }
  1411. }
  1412. catch (e) {
  1413. console.warn('清空所有同步状态失败', e)
  1414. }
  1415. }
  1416. // 获取导入导出功能
  1417. const { readJSON, exportJSON2, getFile, getFile2 } = useImport()
  1418. // 根据iframe的URL查找对应的幻灯片索引
  1419. const findSlideIndexByIframeUrl = (iframeUrl: string): number => {
  1420. try {
  1421. console.log('查找iframe对应的幻灯片索引,iframe URL:', iframeUrl)
  1422. // 遍历所有幻灯片,查找包含该iframe URL的幻灯片
  1423. for (let i = 0; i < slides.value.length; i++) {
  1424. const slide = slides.value[i]
  1425. // 检查幻灯片的元素中是否有iframe
  1426. if (slide.elements && slide.elements.length > 0) {
  1427. for (const element of slide.elements) {
  1428. // 检查是否是iframe元素
  1429. if (element.type === ElementTypes.FRAME) {
  1430. // 检查iframe的src是否匹配
  1431. if (element.url === iframeUrl) {
  1432. console.log(`找到匹配的幻灯片,索引: ${i}, 幻灯片ID: ${slide.id}`)
  1433. return i
  1434. }
  1435. }
  1436. }
  1437. }
  1438. }
  1439. // 如果没有找到匹配的幻灯片,返回当前幻灯片索引
  1440. console.log('未找到匹配的幻灯片,使用当前幻灯片索引:', slideIndex.value)
  1441. return slideIndex.value
  1442. }
  1443. catch (error) {
  1444. console.error('查找幻灯片索引时出错:', error)
  1445. return slideIndex.value
  1446. }
  1447. }
  1448. // 处理iframe链接,为包含workPage的iframe添加必要参数
  1449. // 处理iframe链接,为包含workPage的iframe添加必要参数
  1450. const processIframeLinks = async () => {
  1451. try {
  1452. console.log('开始处理iframe链接')
  1453. console.log('当前props:', { courseid: props.courseid, userid: props.userid })
  1454. // 从slides数据中查找包含iframe的元素
  1455. let hasIframe = false
  1456. // 由于有异步操作,需整体用Promise.all处理
  1457. const updatedSlides = await Promise.all(
  1458. slides.value.map(async (slide, slideIndex) => {
  1459. if (slide.elements && slide.elements.length > 0) {
  1460. // 这里不能直接用async map,否则会导致类型不对
  1461. const updatedElements = await Promise.all(
  1462. slide.elements.map(async (element) => {
  1463. // 检查是否是iframe元素
  1464. if (element.type === ElementTypes.FRAME && element.url) {
  1465. const { element: updatedElement, hasIframe: updatedHasIframe } = await elementDone(element, slideIndex)
  1466. // hasIframe = updatedHasIframe
  1467. hasIframe = true
  1468. console.log('更新后的iframe元素:', updatedElement)
  1469. return {
  1470. ...updatedElement,
  1471. isDone: true
  1472. }
  1473. }
  1474. // 不是iframe元素或不需要处理,直接返回
  1475. return element
  1476. })
  1477. )
  1478. // 返回更新后的幻灯片
  1479. return {
  1480. ...slide,
  1481. elements: updatedElements
  1482. }
  1483. }
  1484. // 没有元素的幻灯片直接返回
  1485. return slide
  1486. })
  1487. )
  1488. if (hasIframe) {
  1489. console.log('找到iframe元素,更新slides数据')
  1490. // 更新store中的slides数据
  1491. slidesStore.setSlides(updatedSlides)
  1492. console.log('slides数据更新完成')
  1493. }
  1494. else {
  1495. console.log('未找到包含workPage的iframe元素')
  1496. }
  1497. console.log('iframe链接处理完成')
  1498. }
  1499. catch (error) {
  1500. console.error('处理iframe链接时出错:', error)
  1501. }
  1502. }
  1503. const elementDone = async (element: any, slideIndex: number) => {
  1504. let hasIframe = false
  1505. let _element = {...element}
  1506. let iframeSrc = element.url
  1507. const toolType = element.toolType
  1508. console.log('当前版本:', currentVersion)
  1509. // 替换beta环境域名
  1510. iframeSrc = iframeSrc.replace(/https?:\/\/beta\.pbl\.cocorobo\.cn/g, 'https://pbl.cocorobo.cn')
  1511. // 根据当前版本统一域名
  1512. const versionMap = {
  1513. cn: /cocorobo\.(hk|com)/g,
  1514. hk: /cocorobo\.(cn|com)/g,
  1515. com: /cocorobo\.(cn|hk)/g
  1516. }
  1517. const targetDomain = `cocorobo.${currentVersion}`
  1518. iframeSrc = iframeSrc.replace(versionMap[currentVersion], targetDomain)
  1519. if (iframeSrc.includes('setWorkPage')) {
  1520. iframeSrc = iframeSrc.replace(/setWorkPage/g, 'workPageNew')
  1521. }
  1522. if (iframeSrc.includes('workPage')) {
  1523. hasIframe = true
  1524. console.log(`处理幻灯片 ${slideIndex + 1} 中的iframe链接:`, iframeSrc)
  1525. try {
  1526. // 解析URL,处理hash部分
  1527. let baseUrl = iframeSrc
  1528. let hashPart = ''
  1529. // 分离base URL和hash部分
  1530. if (iframeSrc.includes('#')) {
  1531. const parts = iframeSrc.split('#')
  1532. baseUrl = parts[0]
  1533. hashPart = parts[1]
  1534. // 去除hashPart中的userid参数
  1535. if (hashPart.includes('userid=')) {
  1536. hashPart = hashPart.replace(/[?&]userid=[^&]+/g, '').replace(/^&/, '?')
  1537. }
  1538. }
  1539. // 构建新的hash部分,添加参数
  1540. // 使用当前幻灯片索引作为task参数
  1541. let newHash = hashPart
  1542. if (newHash.includes('?')) {
  1543. // 如果hash中已经有查询参数,添加&
  1544. newHash += `&courseid=${props.courseid || ''}&userid=${props.userid || ''}&stage=0&task=${slideIndex}&tool=0&cid=${props.cid || ''}`
  1545. }
  1546. else {
  1547. // 如果hash中没有查询参数,添加?
  1548. newHash += `?courseid=${props.courseid || ''}&userid=${props.userid || ''}&stage=0&task=${slideIndex}&tool=0&cid=${props.cid || ''}`
  1549. }
  1550. // 构建新的URL
  1551. let newUrl = `${baseUrl}#${newHash}`
  1552. console.log(`幻灯片 ${slideIndex + 1} 的iframe链接已更新:`, newUrl)
  1553. if (window.location.href.includes('beta') && !newUrl.includes('beta')) {
  1554. newUrl = newUrl.replace('pbl.cocorobo.cn', 'beta.pbl.cocorobo.cn')
  1555. }
  1556. else if (newUrl.includes('beta') && !window.location.href.includes('beta')) {
  1557. newUrl = newUrl.replace('beta.pbl.cocorobo.cn', 'pbl.cocorobo.cn')
  1558. }
  1559. // 返回更新后的元素
  1560. _element = {
  1561. ...element,
  1562. url: newUrl
  1563. }
  1564. }
  1565. catch (error) {
  1566. console.error(`处理幻灯片 ${slideIndex + 1} 的iframe链接时出错:`, error)
  1567. return {
  1568. element: _element,
  1569. hasIframe
  1570. }
  1571. }
  1572. }
  1573. else if (iframeSrc.includes('aichat.cocorobo') || iframeSrc.includes('knowledge.cocorobo')) {
  1574. hasIframe = true
  1575. try {
  1576. // 解析URL,处理hash部分
  1577. let baseUrl = iframeSrc
  1578. let hashPart = ''
  1579. let isHashPart = false
  1580. // 分离base URL和hash部分
  1581. if (iframeSrc.includes('#')) {
  1582. const parts = iframeSrc.split('#')
  1583. baseUrl = parts[0]
  1584. hashPart = parts[1]
  1585. isHashPart = true
  1586. }
  1587. // 构建新的hash部分,添加参数
  1588. // 使用当前幻灯片索引作为task参数
  1589. let newHash = hashPart
  1590. if (newHash.includes('?')) {
  1591. // 如果hash中已经有查询参数,添加&
  1592. newHash += `&courseid=${props.courseid || ''}&layout=laptop`
  1593. }
  1594. else {
  1595. // 如果hash中没有查询参数,添加?
  1596. newHash += `?courseid=${props.courseid || ''}&layout=laptop`
  1597. }
  1598. // 构建新的URL
  1599. let newUrl = `${baseUrl}#${newHash}`
  1600. if (!isHashPart) {
  1601. newUrl = `${baseUrl}${newHash}`
  1602. }
  1603. console.log(`幻灯片 ${slideIndex + 1} 的iframe链接已更新:`, newUrl)
  1604. // 返回更新后的元素
  1605. _element = {
  1606. ...element,
  1607. url: newUrl
  1608. }
  1609. }
  1610. catch (error) {
  1611. console.error(`处理幻灯片 ${slideIndex + 1} 的iframe链接时出错:`, error)
  1612. return {
  1613. element: _element,
  1614. hasIframe
  1615. }
  1616. }
  1617. }
  1618. else if (toolType === 76) {
  1619. hasIframe = true
  1620. try {
  1621. // 解析URL,处理hash部分
  1622. let baseUrl = iframeSrc
  1623. let hashPart = ''
  1624. // 分离base URL和hash部分
  1625. if (iframeSrc.includes('#')) {
  1626. const parts = iframeSrc.split('#')
  1627. baseUrl = parts[0]
  1628. hashPart = parts[1]
  1629. }
  1630. // 构建新的hash部分,添加参数
  1631. // 使用当前幻灯片索引作为task参数
  1632. let newHash = hashPart
  1633. if (newHash.includes('?')) {
  1634. // 如果hash中已经有查询参数,添加&
  1635. newHash += `&mode=pptMode`
  1636. }
  1637. else {
  1638. // 如果hash中没有查询参数,添加?
  1639. newHash += `?mode=pptMode`
  1640. }
  1641. // 构建新的URL
  1642. const newUrl = `${baseUrl}#${newHash}`
  1643. console.log(`幻灯片 ${slideIndex + 1} 的iframe链接已更新:`, newUrl)
  1644. // 返回更新后的元素
  1645. _element = {
  1646. ...element,
  1647. url: newUrl
  1648. }
  1649. }
  1650. catch (error) {
  1651. console.error(`处理幻灯片 ${slideIndex + 1} 的iframe链接时出错:`, error)
  1652. return {
  1653. element: _element,
  1654. hasIframe
  1655. }
  1656. }
  1657. }
  1658. else if (toolType === 73) {
  1659. hasIframe = true
  1660. // 先尝试获取iframe的contentWindow,如果获取不到再使用HTML方式
  1661. try {
  1662. // 创建一个临时的iframe来测试是否能获取contentWindow
  1663. const tempIframe = document.createElement('iframe')
  1664. tempIframe.style.display = 'none'
  1665. tempIframe.src = iframeSrc
  1666. // 先将临时iframe添加到body,否则onload事件不会触发
  1667. document.body.appendChild(tempIframe)
  1668. // 等待iframe加载完成
  1669. await new Promise((resolve, reject) => {
  1670. tempIframe.onload = resolve
  1671. tempIframe.onerror = reject
  1672. // 可选:设置超时时间,避免长时间无响应
  1673. setTimeout(() => reject(new Error('Timeout')), 5000)
  1674. })
  1675. // 尝试获取contentWindow
  1676. if (tempIframe.contentWindow && tempIframe.contentWindow.document) {
  1677. console.log(`iframe ${iframeSrc} 可以获取contentWindow,使用直接加载方式`)
  1678. // 移除临时iframe
  1679. document.body.removeChild(tempIframe)
  1680. _element = {
  1681. ...element,
  1682. isHTML: false,
  1683. url: iframeSrc
  1684. }
  1685. }
  1686. else {
  1687. // 加载完成但无法获取contentWindow,也要移除iframe
  1688. document.body.removeChild(tempIframe)
  1689. }
  1690. }
  1691. catch (error) {
  1692. console.log(`iframe ${iframeSrc} 无法获取contentWindow,使用HTML方式:`, error)
  1693. // 如果无法获取contentWindow,使用HTML方式
  1694. let html = null
  1695. try {
  1696. html = await api.getHTML(iframeSrc)
  1697. console.log('getHTML 成功获取内容:', html)
  1698. }
  1699. catch (error) {
  1700. console.log(`getHTML 失败,尝试使用 getFile:`, error)
  1701. try {
  1702. const fileData = await getFile(iframeSrc)
  1703. if (fileData && fileData.data) {
  1704. const uint8Array = new Uint8Array(fileData.data)
  1705. html = new TextDecoder('utf-8').decode(uint8Array)
  1706. console.log('getFile 成功获取内容:', html)
  1707. }
  1708. }
  1709. catch (error2) {
  1710. console.log(`getFile 失败,尝试使用 getHTML:`, error2)
  1711. try {
  1712. const fileData2 = await getFile2(iframeSrc)
  1713. if (fileData2 && fileData2.data) {
  1714. const uint8Array = new Uint8Array(fileData2.data)
  1715. html = new TextDecoder('utf-8').decode(uint8Array)
  1716. console.log('getFile2 成功获取内容:', html)
  1717. }
  1718. }
  1719. catch (error3) {
  1720. console.error('getFile2 也失败:', error3)
  1721. console.error('无法获取内容: getFile、getFile2 和 getHTML 都失败了')
  1722. }
  1723. }
  1724. }
  1725. console.log(`处理幻灯片 ${slideIndex + 1} 中的iframe链接:`, iframeSrc)
  1726. _element = {
  1727. ...element,
  1728. isHTML: true,
  1729. url: html,
  1730. curl: iframeSrc
  1731. }
  1732. }
  1733. }
  1734. return {
  1735. element: _element,
  1736. hasIframe
  1737. }
  1738. }
  1739. // 导入JSON功能
  1740. const importJSON = (jsonData: any) => {
  1741. try {
  1742. console.log('Student importJSON 开始执行')
  1743. const result = readJSON(jsonData, true)
  1744. if (result.success) {
  1745. console.log('Student importJSON 成功,开始重新渲染')
  1746. // 强制重新渲染:先隐藏组件
  1747. showSlideList.value = false
  1748. // 重新计算画布尺寸和缩放比例
  1749. nextTick(() => {
  1750. calculateScale()
  1751. // 延迟500ms后重新显示组件,确保重新渲染完成
  1752. setTimeout(() => {
  1753. showSlideList.value = true
  1754. // 只有当当前页面存在iframe时才获取作业数据
  1755. if (currentSlideHasIframe.value) { // && props.type == '1'
  1756. getWork()
  1757. }
  1758. selectCourseSLook(1)
  1759. console.log('组件重新渲染完成')
  1760. }, 500)
  1761. })
  1762. return true
  1763. }
  1764. console.error('Student importJSON 失败:', result.error)
  1765. return false
  1766. }
  1767. catch (error) {
  1768. console.error('Student importJSON 执行失败:', error)
  1769. return false
  1770. }
  1771. }
  1772. // 导出JSON功能
  1773. const exportJSON = () => {
  1774. try {
  1775. console.log('Student exportJSON 开始执行,调用 useImport.exportJSON2')
  1776. // 直接调用 useImport 中的 exportJSON2 函数
  1777. const exportData = exportJSON2()
  1778. if (exportData) {
  1779. return exportData
  1780. }
  1781. console.error('Student exportJSON 失败: exportJSON2 返回空数据')
  1782. return false
  1783. }
  1784. catch (error) {
  1785. console.error('Student exportJSON 执行失败:', error)
  1786. return false
  1787. }
  1788. }
  1789. // 返回编辑器
  1790. const backToEditor = () => {
  1791. // 通过路由跳转到编辑模式
  1792. window.location.href = '/'
  1793. }
  1794. const submitWork = async (slideIndex: number, atool: string, content: string, type: string) => {
  1795. const res = await api.submitWork({
  1796. uid: props.userid as string,
  1797. cid: props.courseid as string,
  1798. stage: '0',
  1799. task: String(slideIndex), // 转为字符串
  1800. tool: '0',
  1801. atool: atool,
  1802. content: content,
  1803. type: type
  1804. })
  1805. getWork()
  1806. console.log(res)
  1807. }
  1808. // 文件上传到AWS S3的函数
  1809. const uploadFile = (file: File): Promise<string> => {
  1810. return new Promise((resolve, reject) => {
  1811. try {
  1812. // 检查AWS SDK是否可用
  1813. if (!(window as any).AWS) {
  1814. reject(new Error('AWS SDK not loaded'))
  1815. return
  1816. }
  1817. const credentials = {
  1818. accessKeyId: 'AKIATLPEDU37QV5CHLMH',
  1819. secretAccessKey: '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'
  1820. }
  1821. // 配置AWS
  1822. ;(window as any).AWS.config.update(credentials)
  1823. ;(window as any).AWS.config.region = 'cn-northwest-1'
  1824. // 创建S3实例
  1825. const bucket = new (window as any).AWS.S3({ params: { Bucket: 'ccrb' } })
  1826. if (file) {
  1827. // 生成唯一的文件名
  1828. const fileExtension = file.name.split('.').pop()
  1829. const fileName = `${file.name.split('.')[0]}_${Date.now()}.${fileExtension}`
  1830. const params = {
  1831. Key: fileName,
  1832. ContentType: file.type,
  1833. Body: file,
  1834. ACL: 'public-read'
  1835. }
  1836. const options = {
  1837. partSize: 5 * 1024 * 1024, // 2GB分片
  1838. queueSize: 2,
  1839. leavePartsOnError: true
  1840. }
  1841. bucket
  1842. .upload(params, options)
  1843. .on('httpUploadProgress', (evt: any) => {
  1844. // 这里可以添加进度条逻辑
  1845. const progress = Math.round((evt.loaded * 100) / evt.total)
  1846. console.log(`Uploaded: ${progress}%`)
  1847. })
  1848. .send((err: any, data: any) => {
  1849. if (err) {
  1850. console.error('Upload failed:', err)
  1851. message.error(lang.ssFileUploadFail)
  1852. reject(err)
  1853. }
  1854. else {
  1855. console.log('Upload successful:', data.Location)
  1856. resolve(data.Location)
  1857. }
  1858. })
  1859. }
  1860. else {
  1861. reject(new Error('No file provided'))
  1862. }
  1863. }
  1864. catch (error) {
  1865. console.error('Upload error:', error)
  1866. reject(error)
  1867. }
  1868. })
  1869. }
  1870. // 作业提交功能(优化版)
  1871. const handleHomeworkSubmit = async () => {
  1872. console.log('作业提交按钮被点击')
  1873. // 防抖:如果正在提交中,直接返回
  1874. if (isSubmitting.value) {
  1875. console.log('作业正在提交中,忽略重复点击')
  1876. return
  1877. }
  1878. isSubmitting.value = true
  1879. let homeworkContent: string = lang.ssHwSubmit // 默认作业内容
  1880. let hasSubmitWork = false // 标记是否成功提交作业
  1881. try {
  1882. // 获取所有iframe元素
  1883. const iframes = document.querySelectorAll('.viewer-canvas .screen-slide')[slideIndex.value].querySelectorAll('iframe')
  1884. console.log('找到iframe元素数量:', iframes.length)
  1885. if (iframes.length === 0) {
  1886. message.warning('当前页面没有找到iframe元素')
  1887. return
  1888. }
  1889. for (let i = 0; i < iframes.length; i++) {
  1890. const iframe = iframes[i] as HTMLIFrameElement
  1891. const iframeSrc = iframe.src
  1892. console.log(`iframe ${i + 1} 链接:`, iframeSrc)
  1893. // 检查iframe链接是否包含workPage
  1894. if (iframeSrc && iframeSrc.includes('workPage')) {
  1895. console.log('找到包含workPage的iframe,尝试执行submitWork')
  1896. try {
  1897. const iframeWindow = iframe.contentWindow as Window & { submitWork?: (...args: any[]) => unknown }
  1898. if (iframeWindow && typeof iframeWindow.submitWork === 'function') {
  1899. console.log('执行iframe中的submitWork方法,参数可变')
  1900. const iframeSlideIndex = slideIndex.value
  1901. const submitArgs = [iframeSlideIndex]
  1902. // 支持同步和异步submitWork
  1903. const result = await iframeWindow.submitWork(...submitArgs)
  1904. console.log('submitWork同步执行完成')
  1905. // 尝试从结果中获取作业内容
  1906. if (result && typeof result === 'object') {
  1907. homeworkContent = JSON.stringify(result)
  1908. }
  1909. else if (result) {
  1910. homeworkContent = String(result)
  1911. }
  1912. else {
  1913. homeworkContent = lang.ssHwSubmitWp
  1914. }
  1915. messageInstructionRef.value.success(lang.ssHwSubmitSucc)
  1916. hasSubmitWork = true
  1917. // 发送作业提交成功的socket消息
  1918. sendMessage({
  1919. type: 'homework_submitted',
  1920. courseid: props.courseid,
  1921. slideIndex: slideIndex.value,
  1922. userid: props.userid
  1923. })
  1924. break
  1925. }
  1926. else {
  1927. console.log('iframe中没有找到submitWork方法')
  1928. isSubmitting.value = false
  1929. }
  1930. }
  1931. catch (error) {
  1932. console.error('访问iframe内容时出错:', error)
  1933. isSubmitting.value = false
  1934. }
  1935. }
  1936. else if (iframeSrc && (iframeSrc.includes('aichat.cocorobo') || iframeSrc.includes('knowledge.cocorobo'))) {
  1937. console.log('找到包含aichat.cocorobo或knowledge.cocorobo的iframe,尝试执行submitWork')
  1938. // 由于TS类型检查,需通过 any 绕过类型限制
  1939. const iframeWindow = iframe.contentWindow as any
  1940. if (iframeWindow && iframeWindow.exposed_outputs) {
  1941. if (iframeWindow.exposed_outputs.length === 0) {
  1942. message.warning('没有找到作业内容')
  1943. hasSubmitWork = true
  1944. continue
  1945. }
  1946. console.log('执行iframe中的submitWork方法,参数可变')
  1947. const iframeSlideIndex = slideIndex.value
  1948. const jsonString = JSON.stringify(iframeWindow.exposed_outputs)
  1949. // 将 JSON 字符串转成文件并上传
  1950. try {
  1951. const blob = new Blob([jsonString], { type: 'application/json' })
  1952. const file = new File([blob], `ai_work_${Date.now()}.json`, { type: 'application/json' })
  1953. const fileUrl = await uploadFile(file)
  1954. console.log('文件上传成功,链接:', fileUrl)
  1955. homeworkContent = fileUrl // 保存AI作业内容
  1956. // 使用上传后的链接提交作业
  1957. await submitWork(iframeSlideIndex, '72', fileUrl, '20')
  1958. messageInstructionRef.value.success(lang.ssHwSubmitSucc)
  1959. hasSubmitWork = true
  1960. // 发送作业提交成功的socket消息
  1961. sendMessage({
  1962. type: 'homework_submitted',
  1963. courseid: props.courseid,
  1964. slideIndex: slideIndex.value,
  1965. userid: props.userid
  1966. })
  1967. }
  1968. catch (error) {
  1969. console.error('文件上传失败:', error)
  1970. isSubmitting.value = false
  1971. message.error(lang.ssHwSubmitRetry)
  1972. }
  1973. }
  1974. }
  1975. else if (slides.value[slideIndex.value].elements.some((element: any) => element.isHTML)) {
  1976. message.info(lang.ssTryingScreenshot)
  1977. console.log('尝试截图当前页面并提交ISHTML')
  1978. // return
  1979. try {
  1980. // 尝试使用html2canvas,对iframe支持更好
  1981. let imageData: string
  1982. const screenSlides = document.querySelectorAll('.viewer-canvas .screen-slide')
  1983. let iframeElement: HTMLIFrameElement | null = null
  1984. let iframeBody: HTMLElement | null = null
  1985. let iframehtml: HTMLElement | null = null
  1986. // 获取iframe元素
  1987. if (
  1988. screenSlides &&
  1989. screenSlides[slideIndex.value] &&
  1990. screenSlides[slideIndex.value].querySelector('iframe')
  1991. ) {
  1992. iframeElement = screenSlides[slideIndex.value].querySelector('iframe') as HTMLIFrameElement
  1993. }
  1994. else {
  1995. message.error(lang.ssFailedGetIframe)
  1996. throw new Error('未能获取到iframe元素,无法截图')
  1997. }
  1998. // 获取iframe内部的body元素(同源)
  1999. if (
  2000. iframeElement.contentWindow &&
  2001. iframeElement.contentWindow.document &&
  2002. iframeElement.contentWindow.document.body
  2003. ) {
  2004. // 获取页面的所有注释节点
  2005. const comments = []
  2006. const childNodes = iframeElement.contentWindow.document.createTreeWalker(iframeElement.contentWindow.document.body, NodeFilter.SHOW_COMMENT, null)
  2007. while (childNodes.nextNode()) {
  2008. comments.push(childNodes.currentNode)
  2009. }
  2010. // 移除所有注释节点
  2011. comments.forEach(comment => {
  2012. comment?.parentNode?.removeChild(comment)
  2013. })
  2014. iframeBody = iframeElement.contentWindow.document.body as HTMLElement
  2015. iframehtml = iframeElement.contentWindow.document.getElementsByTagName('html')[0] as HTMLElement
  2016. }
  2017. else {
  2018. message.error(lang.ssFailedGetIframeBody)
  2019. throw new Error('未能获取到iframe的body元素,无法截图')
  2020. }
  2021. try {
  2022. const a = iframeBody.getElementsByTagName('img')
  2023. const b = iframeBody.getElementsByTagName('video')
  2024. // const c = iframeBody.getElementsByTagName('canvas')
  2025. iframeBody.style.cssText += 'width:100%;height:100%;position:absolute;top:0;left:0;'
  2026. iframehtml.style.cssText += 'width:100%;height:100%;position:absolute;top:0;left:0;'
  2027. for (let i = 0;i < a.length;i++) {
  2028. a[i].crossOrigin = 'anonymous'
  2029. }
  2030. for (let i = 0;i < b.length;i++) {
  2031. b[i].crossOrigin = 'anonymous'
  2032. }
  2033. // 1. 创建全局禁用动画的 style 标签
  2034. const style = document.createElement('style')
  2035. style.id = 'html2canvas-freeze'
  2036. style.textContent = `
  2037. *, *::before, *::after {
  2038. animation: none !important;
  2039. transition: none !important;
  2040. opacity: 1 !important;
  2041. }
  2042. `
  2043. iframeElement.contentWindow.document.head.appendChild(style)
  2044. // 2. 强制重排,确保禁用生效
  2045. iframeElement.contentWindow.document.body.offsetHeight
  2046. // 3. 如果词云图使用 ECharts 且存在,等它渲染稳定
  2047. if (typeof iframeElement.contentWindow.myChart !== 'undefined' && iframeElement.contentWindow.myChart && !iframeElement.contentWindow.myChart.isDisposed()) {
  2048. // 延迟 500ms 等待 ECharts 内部的 Canvas 动画结束
  2049. await new Promise(resolve => setTimeout(resolve, 500))
  2050. }
  2051. try {
  2052. // 直接对iframe内部的body进行截图
  2053. const html2canvas = await import('html2canvas')
  2054. const canvas = await html2canvas.default(iframeBody, {
  2055. // useCORS: true,
  2056. // allowTaint: true,
  2057. // scale: 1,
  2058. // backgroundColor: '#ffffff',
  2059. // logging: false,
  2060. // foreignObjectRendering: true,
  2061. // removeContainer: true
  2062. scale: 2, // 提高清晰度
  2063. allowTaint: false, // 是否允许跨域污染画布
  2064. useCORS: true, // 尝试跨域加载图片
  2065. logging: true,
  2066. })
  2067. imageData = canvas.toDataURL('image/png', 0.95)
  2068. }
  2069. finally {
  2070. const freezeStyle = iframeElement.contentWindow.document.getElementById('html2canvas-freeze')
  2071. if (freezeStyle) freezeStyle.remove()
  2072. }
  2073. console.log('成功截图iframe内部内容')
  2074. }
  2075. catch (html2canvasError) {
  2076. console.log('html2canvas失败,尝试html-to-image:', html2canvasError)
  2077. message.error(lang.ssHtml2canvasFailed + html2canvasError)
  2078. try {
  2079. // 回退到html-to-image
  2080. const { toPng } = await import('html-to-image')
  2081. imageData = await toPng(iframeBody, {
  2082. quality: 0.95,
  2083. backgroundColor: '#ffffff',
  2084. filter: (node) => {
  2085. if (node.tagName === 'SCRIPT' || node.tagName === 'STYLE') {
  2086. return false
  2087. }
  2088. return true
  2089. }
  2090. })
  2091. console.log('使用html-to-image截图成功')
  2092. }
  2093. catch (htmlToImageError) {
  2094. console.log('html-to-image也失败了,使用canvas绘制方案:', htmlToImageError)
  2095. message.error(lang.ssHtmlToImageFailed + htmlToImageError)
  2096. message.error(lang.ssShotFail)
  2097. return
  2098. /*
  2099. // 最后的备用方案:使用canvas绘制
  2100. const canvas = document.createElement('canvas')
  2101. const ctx = canvas.getContext('2d')
  2102. if (ctx) {
  2103. canvas.width = iframeElement.offsetWidth || 800
  2104. canvas.height = iframeElement.offsetHeight || 600
  2105. // 绘制背景
  2106. const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height)
  2107. gradient.addColorStop(0, '#f8f9fa')
  2108. gradient.addColorStop(1, '#e9ecef')
  2109. ctx.fillStyle = gradient
  2110. ctx.fillRect(0, 0, canvas.width, canvas.height)
  2111. // 绘制边框
  2112. ctx.strokeStyle = '#dee2e6'
  2113. ctx.lineWidth = 3
  2114. ctx.strokeRect(2, 2, canvas.width - 4, canvas.height - 4)
  2115. // 绘制内边框
  2116. ctx.strokeStyle = '#ffffff'
  2117. ctx.lineWidth = 1
  2118. ctx.strokeRect(5, 5, canvas.width - 10, canvas.height - 10)
  2119. // 绘制iframe图标
  2120. ctx.fillStyle = '#6c757d'
  2121. ctx.font = 'bold 48px Arial'
  2122. ctx.textAlign = 'center'
  2123. ctx.fillText('', canvas.width / 2, canvas.height / 2 - 40)
  2124. // 绘制标题
  2125. ctx.font = 'bold 20px Arial'
  2126. ctx.fillStyle = '#495057'
  2127. ctx.fillText('iframe内容', canvas.width / 2, canvas.height / 2 + 20)
  2128. // 绘制URL
  2129. const src = iframeElement.srcf
  2130. if (src) {
  2131. ctx.font = '14px Arial'
  2132. ctx.fillStyle = '#6c757d'
  2133. const url = src.length > 80 ? src.substring(0, 80) + '...' : src
  2134. ctx.fillText(url, canvas.width / 2, canvas.height / 2 + 50)
  2135. }
  2136. // 绘制提示信息
  2137. ctx.font = '12px Arial'
  2138. ctx.fillStyle = '#adb5bd'
  2139. ctx.fillText('(截图失败)', canvas.width / 2, canvas.height / 2 + 80)
  2140. // 绘制装饰性元素
  2141. ctx.strokeStyle = '#dee2e6'
  2142. ctx.lineWidth = 1
  2143. ctx.setLineDash([5, 5])
  2144. ctx.strokeRect(20, 20, canvas.width - 40, canvas.height - 40)
  2145. ctx.setLineDash([])
  2146. imageData = canvas.toDataURL('image/png', 0.95)
  2147. console.log('使用canvas绘制方案截图成功')
  2148. }
  2149. else {
  2150. throw new Error('无法创建canvas上下文')
  2151. }*/
  2152. }
  2153. }
  2154. const _a = iframeBody.getElementsByTagName('img')
  2155. const _b = iframeBody.getElementsByTagName('video')
  2156. for (let i = 0; i < _a.length; i++) {
  2157. _a[i].removeAttribute('crossorigin')
  2158. }
  2159. for (let i = 0; i < _b.length; i++) {
  2160. _b[i].removeAttribute('crossorigin')
  2161. }
  2162. // 将base64字符串转换为File对象
  2163. const base64ToFile = (base64String: string, filename: string): File => {
  2164. const arr = base64String.split(',')
  2165. const mime = arr[0].match(/:(.*?);/)?.[1] || 'image/png'
  2166. const bstr = atob(arr[1])
  2167. let n = bstr.length
  2168. const u8arr = new Uint8Array(n)
  2169. while (n--) {
  2170. u8arr[n] = bstr.charCodeAt(n)
  2171. }
  2172. return new File([u8arr], filename, { type: mime })
  2173. }
  2174. const imageFile = base64ToFile(imageData, `screenshot_${Date.now()}.png`)
  2175. const imageUrl = await uploadFile(imageFile)
  2176. homeworkContent = imageUrl // 保存截图URL作为作业内容
  2177. // 提交截图
  2178. await submitWork(slideIndex.value, '73', imageUrl, '1') // 73表示截图工具,21表示图片类型
  2179. console.log('messageInstructionRef', messageInstructionRef.value)
  2180. messageInstructionRef.value.success(lang.ssShotSucc)
  2181. hasSubmitWork = true
  2182. // 发送作业提交成功的socket消息
  2183. sendMessage({
  2184. type: 'homework_submitted',
  2185. courseid: props.courseid,
  2186. slideIndex: slideIndex.value,
  2187. userid: props.userid
  2188. })
  2189. }
  2190. catch (error) {
  2191. message.error(lang.ssScreenshotSubmitFailed + error)
  2192. console.error('截图提交失败:', error)
  2193. isSubmitting.value = false
  2194. message.error(lang.ssShotFail)
  2195. }
  2196. }
  2197. else {
  2198. // message.info('尝试截图当前页面并提交')
  2199. const screenSlides = document.querySelectorAll('.viewer-canvas .screen-slide')
  2200. let iframeElement: HTMLIFrameElement | null = null
  2201. // 获取iframe元素
  2202. if (
  2203. screenSlides &&
  2204. screenSlides[slideIndex.value] &&
  2205. screenSlides[slideIndex.value].querySelector('iframe')
  2206. ) {
  2207. iframeElement = screenSlides[slideIndex.value].querySelector('iframe') as HTMLIFrameElement
  2208. }
  2209. else {
  2210. message.error(lang.ssFailedGetIframe)
  2211. throw new Error('未能获取到iframe元素,无法截图')
  2212. }
  2213. // 获取iframe内部的body元素(同源)
  2214. if (
  2215. iframeElement.contentWindow &&
  2216. iframeElement.contentWindow.document &&
  2217. iframeElement.contentWindow.document.body
  2218. ) {
  2219. iframeElement.contentWindow.document.body.style.cssText += 'width:100%;height:100%;position:absolute;top:0;left:0;'
  2220. iframeElement.contentWindow.document.getElementsByTagName('html')[0].style.cssText += 'width:100%;height:100%;position:absolute;top:0;left:0;'
  2221. try {
  2222. isSubmitting.value = true
  2223. const _ajs = iframeElement.contentWindow.document.createElement('script')
  2224. _ajs.type = 'text/javascript'
  2225. _ajs.innerHTML =
  2226. 'var _js = document.createElement("script");\n' +
  2227. '_js.type="text/javascript";\n' +
  2228. '_js.src="https://beta.cloud.cocorobo.cn/js/Common/html2canvas-pro.min.js";\n' +
  2229. '_js.onload = function(){\n' +
  2230. ' var a = document.getElementsByTagName("img")\n' +
  2231. ' for(var i = 0;i<a.length;i++){a[i].crossOrigin="anonymous"}\n' +
  2232. ' html2canvas(document.body, {scale: 2,allowTaint: false,useCORS: true,logging: true,}).then(canvas => {\n' +
  2233. ' var base64Url = canvas.toDataURL("image/png");\n' +
  2234. 'var base64 = "<img src=" + base64Url + " />"\n' +
  2235. 'var file = dataURLtoFile_shishi(base64Url, "截图")\n' +
  2236. 'beforeUpload_shishi(file,' +
  2237. "'" +
  2238. props.userid +
  2239. "'" +
  2240. ', ' +
  2241. "'" +
  2242. props.courseid +
  2243. "'" +
  2244. ', ' +
  2245. "'" +
  2246. slideIndex.value +
  2247. "'" +
  2248. ', ' +
  2249. "'0'" +
  2250. ', ' +
  2251. "'73'" +
  2252. ', ' +
  2253. "'1'" +
  2254. ')\n' +
  2255. ' });\n' +
  2256. '}\n' +
  2257. 'document.head.appendChild(_js);\n'
  2258. iframeElement.contentWindow.document.head.appendChild(_ajs)
  2259. return
  2260. }
  2261. catch (error) {
  2262. message.error(lang.ssFailedGetIframeBodyElement)
  2263. throw new Error('获取iframe内部body元素失败,无法截图')
  2264. }
  2265. }
  2266. }
  2267. }
  2268. if (!hasSubmitWork) {
  2269. message.info(lang.ssHwNoFunc)
  2270. }
  2271. else {
  2272. const element = elementList.value.find((i:any) => i.type === 'frame')
  2273. api.addPPTOp2({
  2274. id: props.courseid,
  2275. userid: props.userid || '',
  2276. type: '3',
  2277. index: (element as any).id, // 获取当前ppt页面iframe的id
  2278. data: String(Math.max(0, Math.round((Date.now() - slideEnterTime.value) / 1000))), // 进入作业页面到提交的耗时(秒)
  2279. }).then(res => {
  2280. console.log('res', res)
  2281. })
  2282. }
  2283. isSubmitting.value = false
  2284. }
  2285. catch (error) {
  2286. console.error('作业提交过程中出错:', error)
  2287. message.error('作业提交过程中出错:' + error)
  2288. message.error(lang.ssHwSubmitFail)
  2289. isSubmitting.value = false
  2290. addOp3(1, new Date().getTime(), { courseid: props.courseid, homeworkContent }, 'error')
  2291. }
  2292. finally {
  2293. // isSubmitting.value = false
  2294. getWork(true)
  2295. if (hasSubmitWork) {
  2296. addOp3(1, new Date().getTime(), { courseid: props.courseid, homeworkContent }, 'success')
  2297. }
  2298. else {
  2299. addOp3(1, new Date().getTime(), { courseid: props.courseid, homeworkContent: '未找到可用的作业提交功能' }, 'error')
  2300. }
  2301. }
  2302. }
  2303. const successSubmit = () => {
  2304. messageInstructionRef.value.success(lang.ssHwSubmitSucc)
  2305. sendMessage({
  2306. type: 'homework_submitted',
  2307. courseid: props.courseid,
  2308. slideIndex: slideIndex.value,
  2309. userid: props.userid
  2310. })
  2311. isSubmitting.value = false
  2312. getWork(true)
  2313. }
  2314. const successLike = () => {
  2315. messageInstructionRef.value.success(lang.ssLikeSucc)
  2316. sendMessage({
  2317. type: 'like_updated',
  2318. courseid: props.courseid,
  2319. slideIndex: slideIndex.value,
  2320. userid: props.userid
  2321. })
  2322. getWork(true)
  2323. }
  2324. // 刷新iframe功能
  2325. const handleRefreshPage = () => {
  2326. console.log('刷新iframe按钮被点击')
  2327. try {
  2328. const element = elementList.value.find((i:any) => i.type === 'frame')
  2329. console.log(element)
  2330. if (
  2331. element &&
  2332. typeof element === 'object' &&
  2333. ('toolType' in element) &&
  2334. (element as any).toolType !== undefined &&
  2335. toolTypeArray.value.includes((element as any).toolType)
  2336. ) {
  2337. getWork()
  2338. }
  2339. // 获取当前幻灯片中的所有iframe元素
  2340. const iframes = document.querySelectorAll('.viewer-canvas .screen-slide')[slideIndex.value].querySelectorAll('iframe')
  2341. console.log('找到iframe元素数量:', iframes.length)
  2342. if (iframes.length === 0) {
  2343. message.warning(lang.ssNoIframe)
  2344. return
  2345. }
  2346. let refreshedCount = 0
  2347. // 遍历所有iframe并刷新
  2348. for (let i = 0; i < iframes.length; i++) {
  2349. const iframe = iframes[i] as HTMLIFrameElement
  2350. // 优化刷新方式,避免闪烁和兼容 srcdoc 场景
  2351. if (iframe.src) {
  2352. // 仅当有src属性时刷新
  2353. const originalSrc = iframe.src
  2354. // 通过重新赋值src实现刷新,避免先清空再赋值导致的闪烁
  2355. iframe.src = ''
  2356. setTimeout(() => {
  2357. iframe.src = originalSrc
  2358. console.log(`刷新iframe ${i + 1}:`, originalSrc)
  2359. }, 50)
  2360. refreshedCount++
  2361. }
  2362. else if (iframe.srcdoc) {
  2363. // srcdoc场景下,重新赋值srcdoc内容
  2364. const originalSrcdoc = iframe.srcdoc
  2365. iframe.srcdoc = ''
  2366. setTimeout(() => {
  2367. iframe.srcdoc = originalSrcdoc
  2368. console.log(`iframe ${i + 1} (srcdoc) 刷新完成`)
  2369. }, 50)
  2370. refreshedCount++
  2371. }
  2372. }
  2373. if (refreshedCount > 0) {
  2374. message.success(lang.ssRefreshDone)
  2375. // 如果当前页面有iframe,重新获取作业数据
  2376. if (currentSlideHasIframe.value && props.type == '1') {
  2377. setTimeout(() => {
  2378. getWork()
  2379. }, 500) // 延迟500ms等待iframe加载完成
  2380. }
  2381. isSubmitting.value = false
  2382. }
  2383. else {
  2384. message.info(lang.ssNoIframeRef)
  2385. }
  2386. }
  2387. catch (error) {
  2388. console.error('刷新iframe时出错:', error)
  2389. message.error(lang.ssRefreshFail)
  2390. }
  2391. }
  2392. // 获取作业提交按钮的右侧位置
  2393. const getHomeworkButtonRight = () => {
  2394. if (isFullscreen.value) {
  2395. return 70 // 全屏时按钮在右侧30px
  2396. }
  2397. if (props.type === '1') {
  2398. // 展开回答结果:按钮更靠左;收起时:按钮更靠右侧
  2399. return workPanelCollapsed.value ? 100 : 430
  2400. }
  2401. return 30 // type=2时按钮在右侧30px
  2402. }
  2403. // 获取刷新按钮的右侧位置
  2404. const getRefreshButtonRight = () => {
  2405. if (isFullscreen.value) {
  2406. return 160 // 全屏时按钮在右侧150px
  2407. }
  2408. if (props.type === '1') {
  2409. // 展开回答结果:按钮更靠左;收起时:按钮更靠右侧
  2410. return workPanelCollapsed.value ? 190 : 560
  2411. }
  2412. return 160 // type=2时按钮在右侧150px
  2413. }
  2414. // 键盘快捷键
  2415. const handleKeydown = (e: KeyboardEvent) => {
  2416. // 如果事件发生在输入框中,不处理快捷键
  2417. const target = e.target as HTMLElement
  2418. if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {
  2419. return
  2420. }
  2421. console.log('键盘事件:', e.key)
  2422. switch (e.key) {
  2423. case 'ArrowLeft':
  2424. e.preventDefault()
  2425. if (!isFollowModeActive.value || props.type == '1') {
  2426. previousSlide()
  2427. }
  2428. break
  2429. case 'PageUp':
  2430. case 'ArrowUp':
  2431. e.preventDefault()
  2432. if (!isFollowModeActive.value || props.type == '1') {
  2433. previousSlide()
  2434. }
  2435. break
  2436. case 'ArrowRight':
  2437. e.preventDefault()
  2438. if (!isFollowModeActive.value || props.type == '1') {
  2439. nextSlide()
  2440. }
  2441. break
  2442. case 'PageDown':
  2443. case 'ArrowDown':
  2444. case ' ':
  2445. e.preventDefault()
  2446. if (!isFollowModeActive.value || props.type == '1') {
  2447. nextSlide()
  2448. }
  2449. break
  2450. case 'F11':
  2451. e.preventDefault()
  2452. enterFullscreen()
  2453. break
  2454. case 'Escape':
  2455. if (document.fullscreenElement) {
  2456. document.exitFullscreen()
  2457. }
  2458. break
  2459. default:
  2460. break
  2461. }
  2462. }
  2463. // 事件处理函数
  2464. const handleSlidesDataUpdated = () => {
  2465. console.log('收到 slidesDataUpdated 事件')
  2466. // 强制重新渲染:先隐藏组件
  2467. showSlideList.value = false
  2468. nextTick(() => {
  2469. calculateScale()
  2470. // 延迟500ms后重新显示组件,确保重新渲染完成
  2471. setTimeout(() => {
  2472. showSlideList.value = true
  2473. console.log('组件重新渲染完成')
  2474. // 重新处理iframe链接
  2475. processIframeLinks()
  2476. }, 500)
  2477. console.log('slidesDataUpdated 事件处理完成')
  2478. })
  2479. }
  2480. const handleViewportSizeUpdated = (event: any) => {
  2481. console.log('收到 viewportSizeUpdated 事件:', event.detail)
  2482. // 重新计算缩放比例
  2483. nextTick(() => {
  2484. calculateScale()
  2485. console.log('viewportSizeUpdated 事件处理完成')
  2486. })
  2487. }
  2488. const pptJsonFileid = ref<string>('')
  2489. // 上传文件
  2490. const uploadFile2 = async (file: File, pptid: string): Promise<void> => {
  2491. try {
  2492. const uuid = generateUUID()
  2493. const formData = new FormData()
  2494. const timestamp = Date.now()
  2495. const finalExtension = file.name.split('.').pop()?.toLowerCase() || ''
  2496. const baseName = file.name.slice(0, -(finalExtension.length + 1))
  2497. formData.append(
  2498. 'file',
  2499. new File([file], `${baseName}${timestamp}.${finalExtension}`)
  2500. )
  2501. formData.append('collection_ids', JSON.stringify([]))
  2502. formData.append('id', uuid)
  2503. formData.append('metadata', JSON.stringify({ title: file.name }))
  2504. formData.append('ingestion_mode', 'fast')
  2505. formData.append('run_with_orchestration', 'true')
  2506. // 同步知识库
  2507. await axios.post(
  2508. 'https://r2rserver.cocorobo.cn/v3/documents',
  2509. formData,
  2510. {
  2511. headers: {
  2512. 'Content-Type': 'multipart/form-data',
  2513. },
  2514. }
  2515. )
  2516. const ptype = '1' // 根据实际业务定义类型
  2517. const fileid = uuid // 如果需要唯一fileid可以和pptid保持一致或按需更改
  2518. await axios.post(`${API_URL}addPPTFile`, [{
  2519. pptid: pptid,
  2520. ptype: ptype,
  2521. fileid: fileid,
  2522. classid: '',
  2523. task: '',
  2524. tool: ''
  2525. }])
  2526. }
  2527. catch (err) {
  2528. console.error(err)
  2529. throw err
  2530. }
  2531. }
  2532. const checkPPTFile = async (jsonObj: any) => {
  2533. const res = await api.getPPTFile(props.courseid as string, props.cid as string)
  2534. console.log(res)
  2535. const data1 = res[0]
  2536. const data2 = res[1]
  2537. const data3 = res[2]
  2538. console.log(data1, data2, data3)
  2539. if (res[0].length) {
  2540. pptJsonFileid.value = data1[0].fileid
  2541. }
  2542. else {
  2543. const pptJsonFile = new File([jsonObj], courseDetail.value.title + '.txt', { type: 'text/plain' })
  2544. uploadFile2(pptJsonFile, props.courseid as string)
  2545. }
  2546. }
  2547. const getCourseDetail = async () => {
  2548. isLoading.value = true
  2549. try {
  2550. const res = await api.getCourseDetail(props.courseid as string)
  2551. const opRes1 = await api.selectPPTOp({
  2552. id: props.courseid + '-' + props.cid,
  2553. type: '1',
  2554. index: 0
  2555. })
  2556. opRes.value = opRes1[0]
  2557. console.log('操作记录:', opRes1[0])
  2558. console.log('操作记录:', opRes.value)
  2559. console.log(res, opRes.value)
  2560. const courseData = res[0][0]
  2561. courseDetail.value = courseData
  2562. selectWorksStudent()
  2563. checkIsCreator()
  2564. const pptJSONUrl = JSON.parse(courseData.chapters).pptData ? JSON.parse(courseData.chapters).pptData : ''
  2565. aiAssistant.value = JSON.parse(courseData.chapters).aiAssistant ? JSON.parse(courseData.chapters).aiAssistant : false
  2566. console.log(pptJSONUrl)
  2567. if (pptJSONUrl) {
  2568. const pptdata = await getFile(pptJSONUrl)
  2569. // pptdata.data 是 ArrayBuffer,需要先转成字符串再解析为 JSON
  2570. let jsonStr = ''
  2571. if (pptdata && pptdata.data) {
  2572. // 先将 ArrayBuffer 转为字符串
  2573. const uint8Array = new Uint8Array(pptdata.data)
  2574. jsonStr = new TextDecoder('utf-8').decode(uint8Array)
  2575. try {
  2576. const jsonObj = JSON.parse(jsonStr)
  2577. // 生成每页幻灯片的内容描述
  2578. const pptContent = []
  2579. if (jsonObj.slides) {
  2580. jsonObj.slides.forEach((slide: any, index: number) => {
  2581. let slideContent = ''
  2582. if (slide.elements) {
  2583. // 提取文本内容(包括普通文本和形状文本)
  2584. const allTextElements = slide.elements.filter((element: any) =>
  2585. element.type === 'text' || (element.type === 'shape' && element.text?.content)
  2586. )
  2587. if (allTextElements.length > 0) {
  2588. slideContent = allTextElements
  2589. .map((element: any) => {
  2590. const content = element.type === 'text' ? element.content : element.text.content
  2591. return content.replace(/<[^>]*>/g, '')
  2592. })
  2593. .join(' ')
  2594. }
  2595. }
  2596. pptContent.push(`第${index + 1}页: ${slideContent || '内容为空'}`)
  2597. })
  2598. }
  2599. const contentDescription = pptContent.join('\n')
  2600. checkPPTFile(contentDescription)
  2601. importJSON(jsonObj)
  2602. if (isCreator.value) {
  2603. console.log('jsonObj', jsonObj)
  2604. for (let i = 0; i < jsonObj.slides.length; i++) {
  2605. const notTool = [74, 75, 76, 82]
  2606. const elements = jsonObj.slides[i].elements.some((element: any) => {
  2607. return element.type === 'frame' && !notTool.includes(element.toolType)
  2608. })
  2609. let toolType = 0
  2610. if (jsonObj.slides[i].elements.length && jsonObj.slides[i].elements[0].toolType) {
  2611. toolType = jsonObj.slides[i].elements[0].toolType
  2612. }
  2613. const json = {
  2614. isTool: elements,
  2615. can: false,
  2616. like: false,
  2617. anonymous: false,
  2618. answer: false,
  2619. }
  2620. if (toolType === 78) {
  2621. json.anonymous = true
  2622. }
  2623. isResultArray.value[i] = json
  2624. }
  2625. setIsResultArray()
  2626. // 广播消息
  2627. sendMessage({
  2628. type: 'isResultArray',
  2629. isResultArray: JSON.stringify(isResultArray.value),
  2630. courseid: props.courseid
  2631. })
  2632. console.log(isResultArray.value)
  2633. }
  2634. }
  2635. catch (e) {
  2636. console.error('解析pptdata.data失败:', e)
  2637. }
  2638. }
  2639. }
  2640. getWorkId()
  2641. autoSwitchToAvailablePanel()
  2642. }
  2643. catch (error) {
  2644. console.error('获取课程详情失败:', error)
  2645. message.error(lang.ssFetchCourseFail)
  2646. isLoading.value = false
  2647. }
  2648. finally {
  2649. isLoading.value = false
  2650. // if (props.type == '2') {
  2651. // console.log('判断是否是学生进入全屏')
  2652. // function panFull() {
  2653. // console.log('判断是否是学生进入全屏111')
  2654. // if (!document.fullscreenElement) {
  2655. // setTimeout(() => {
  2656. // if (!document.fullscreenElement) {
  2657. // if (document.documentElement.requestFullscreen) {
  2658. // document.documentElement.requestFullscreen()
  2659. // }
  2660. // else if (document.documentElement.mozRequestFullScreen) { // Firefox
  2661. // document.documentElement.mozRequestFullScreen()
  2662. // }
  2663. // else if (document.documentElement.webkitRequestFullscreen) { // Chrome, Safari and Opera
  2664. // document.documentElement.webkitRequestFullscreen()
  2665. // }
  2666. // else if (document.documentElement.msRequestFullscreen) { // IE/Edge
  2667. // document.documentElement.msRequestFullscreen()
  2668. // }
  2669. // panFull()
  2670. // }
  2671. // }, 50)
  2672. // }
  2673. // }
  2674. // nextTick(() => {
  2675. // setTimeout(() => {
  2676. // // enterFullscreen();
  2677. // panFull()
  2678. // }, 50)
  2679. // })
  2680. // }
  2681. }
  2682. }
  2683. const getWorkLoading = ref<any>(false)
  2684. const getWork = async (isUpdate = false) => {
  2685. try {
  2686. if (getWorkLoading.value) {
  2687. return
  2688. }
  2689. if (!isUpdate) {
  2690. workLoading.value = true
  2691. }
  2692. getWorkLoading.value = true
  2693. console.log('getWork 开始执行,参数:', {
  2694. courseid: props.courseid,
  2695. slideIndex: slideIndex.value,
  2696. type: props.type,
  2697. isUpdate
  2698. })
  2699. if (!props.courseid) {
  2700. console.warn('getWork: courseid 未提供,跳过执行')
  2701. if (!isUpdate) workLoading.value = false
  2702. return
  2703. }
  2704. const res = await api.selectSWorks(props.courseid, '0', slideIndex.value.toString())
  2705. console.log('getWork 执行成功,结果:', res)
  2706. const frame = elementList.value.find(element => element.type === ElementTypes.FRAME)
  2707. console.log('frame:', frame)
  2708. const toolType = frame?.toolType ?? ''
  2709. const likeArray = res[1]
  2710. console.log('likeArray', likeArray)
  2711. const newWorkArray = props.cid
  2712. ? res[0].filter((work: any) => {
  2713. // 修复:使用 === 严格相等比较,避免类型转换导致的意外结果
  2714. // 只有当 ttype == '1' 或 (ttype == '2' 且 classid 包含 props.cid) 时才保留
  2715. // 同时满足 atool === toolType 或 toolType 为空
  2716. // return (work.ttype == '1' || (work.ttype == '2' && work.classid.includes(props.cid))) && (work.atool == toolType.value || !toolType.value)
  2717. // work.ttype == '1'
  2718. const ttypeMatch = work.ttype == '1' || (work.ttype == '2' && work.classid && work.classid.includes(props.cid))
  2719. const toolMatch = toolType ? work.atool == toolType : true
  2720. return ttypeMatch && toolMatch
  2721. }).map((work: any) => {
  2722. // 计算点赞数量:likeArray中wid等于当前work.id的记录数
  2723. const likesCount = likeArray.filter((like: any) => like.workId === work.id).length
  2724. // 判断当前用户是否点赞:likeArray中wid等于当前work.id且likesId等于当前用户id
  2725. const isLikes = likeArray.some((like: any) => like.workId === work.id && like.likesId === props.userid)
  2726. return {
  2727. ...work,
  2728. likesCount,
  2729. isLikes
  2730. }
  2731. })
  2732. : res[0].map((work: any) => {
  2733. // 计算点赞数量:likeArray中wid等于当前work.id的记录数
  2734. const likesCount = likeArray.filter((like: any) => like.workId === work.id).length
  2735. // 判断当前用户是否点赞:likeArray中wid等于当前work.id且likesId等于当前用户id
  2736. const isLikes = likeArray.some((like: any) => like.workId === work.id && like.likesId === props.userid)
  2737. return {
  2738. ...work,
  2739. likesCount,
  2740. isLikes
  2741. }
  2742. })
  2743. // 如果是更新模式,只有当数据真正变化时才更新
  2744. if (isUpdate) {
  2745. const hasChanged = checkWorkArrayChanged(workArray.value, newWorkArray)
  2746. if (hasChanged) {
  2747. console.log('检测到作业数据变化,更新显示')
  2748. workArray.value = newWorkArray
  2749. }
  2750. else {
  2751. console.log('作业数据无变化,跳过更新')
  2752. }
  2753. }
  2754. else {
  2755. workArray.value = newWorkArray
  2756. }
  2757. console.log('getWork 执行成功,结果:', workArray.value)
  2758. getWorkLoading.value = false
  2759. }
  2760. catch (error) {
  2761. console.error('getWork 执行失败:', error)
  2762. if (!isUpdate) {
  2763. message.error(lang.ssWorkInfoFail)
  2764. }
  2765. getWorkLoading.value = false
  2766. }
  2767. finally {
  2768. if (!isUpdate) {
  2769. workLoading.value = false
  2770. }
  2771. getWorkLoading.value = false
  2772. }
  2773. }
  2774. const selectWorksStudent = async () => {
  2775. studentLoading.value = true
  2776. try {
  2777. const res = await api.selectWorksStudent(props.oid as string, courseDetail.value.juri as string)
  2778. console.log('selectWorksStudent', res)
  2779. const students = res[0]
  2780. console.log('students', students)
  2781. if (props.cid) {
  2782. studentArray.value = students.filter((student: any) => student.classid.includes(props.cid))
  2783. }
  2784. else {
  2785. studentArray.value = students
  2786. }
  2787. }
  2788. catch (error) {
  2789. console.error('获取学生信息失败:', error)
  2790. message.error(lang.ssStuInfoFail)
  2791. }
  2792. finally {
  2793. studentLoading.value = false
  2794. }
  2795. }
  2796. // 检查作业数组是否发生变化
  2797. const checkWorkArrayChanged = (oldArray: WorkItem[], newArray: WorkItem[]): boolean => {
  2798. if (oldArray.length !== newArray.length) return true
  2799. // 检查每个作业的 id 和 name 是否一致
  2800. for (let i = 0; i < oldArray.length; i++) {
  2801. const oldWork = oldArray[i]
  2802. const newWork = newArray[i]
  2803. if (oldWork.id !== newWork.id || oldWork.name !== newWork.name || oldWork.content !== newWork.content || oldWork.isLikes !== newWork.isLikes || oldWork.likesCount !== newWork.likesCount) {
  2804. return true
  2805. }
  2806. }
  2807. return false
  2808. }
  2809. // 查询课程跟随状态
  2810. const selectCourseSLook = async (type = 2) => {
  2811. const res = await api.selectCourseSLook(props.courseid as string)
  2812. console.log('selectCourseSLook', res)
  2813. if (res[0][0].follow == 2) {
  2814. if (props.type == '2') {
  2815. goToSlide(Number(res[0][0].followC))
  2816. }
  2817. isFollowModeActive.value = true
  2818. if (props.userid == courseDetail.value.userid && props.type == '1') {
  2819. api.updateCourseFollowC(slideIndex.value, props.courseid as string)
  2820. sendMessage({slideIndex: slideIndex.value, courseid: props.courseid, type: 'slideIndex'})
  2821. console.log('设置当前幻灯片为跟随目标:', slideIndex.value)
  2822. }
  2823. if (props.type == '2' && slidePanelCollapsed.value) {
  2824. slidePanelCollapsed.value = false
  2825. }
  2826. }
  2827. else {
  2828. isFollowModeActive.value = false
  2829. if (type === 1 && props.userid == courseDetail.value.userid && props.type == '1') {
  2830. toggleFollowMode()
  2831. }
  2832. }
  2833. if (props.type == '2') {
  2834. message.success(isFollowModeActive.value ? lang.ssFollowOnTip : lang.ssFreeOnTip)
  2835. }
  2836. checkParentMode()
  2837. }
  2838. // 切换跟随模式
  2839. const toggleFollowMode = async () => {
  2840. try {
  2841. const newFollowState = !isFollowModeActive.value
  2842. const sopen = newFollowState ? 2 : 1
  2843. // 调用API更新跟随状态
  2844. const res = await api.updateCourseFollow(sopen, props.courseid as string)
  2845. console.log('更新跟随模式状态:', res)
  2846. sendMessage({sopen: newFollowState, courseid: props.courseid, type: 'sopen'})
  2847. if (res) {
  2848. isFollowModeActive.value = newFollowState
  2849. message.success(newFollowState ? lang.ssFollowOnTip : lang.ssFreeOnTip)
  2850. // 如果开启跟随模式,设置当前幻灯片为跟随目标
  2851. if (newFollowState) {
  2852. await api.updateCourseFollowC(slideIndex.value, props.courseid as string)
  2853. console.log('设置当前幻灯片为跟随目标:', slideIndex.value)
  2854. }
  2855. if (timerlVisible.value) {
  2856. timerlVisible.value = false
  2857. }
  2858. handleWritingBoardClose()
  2859. }
  2860. else {
  2861. message.error(lang.ssOpFailRetry)
  2862. }
  2863. checkParentMode()
  2864. }
  2865. catch (error) {
  2866. console.error('切换跟随模式失败:', error)
  2867. message.error(lang.ssOpFailRetry)
  2868. }
  2869. }
  2870. const checkParentMode = () => {
  2871. // @ts-ignore
  2872. if (window.parent && typeof window.parent.onFreeBrowseChange === 'function') {
  2873. // @ts-ignore
  2874. window.parent.onFreeBrowseChange(!isFollowModeActive.value)
  2875. }
  2876. }
  2877. const setIsResultArray = () => {
  2878. // @ts-ignore
  2879. if (window.parent && typeof window.parent.setIsResultArray === 'function') {
  2880. // @ts-ignore
  2881. window.parent.setIsResultArray(isResultArray.value)
  2882. }
  2883. }
  2884. const setIsResultArray2 = (value: boolean, key: string) => {
  2885. isResultArray.value[slideIndex.value][key] = value
  2886. console.log(isResultArray.value)
  2887. // @ts-ignore
  2888. if (window.parent && typeof window.parent.setIsResultArray === 'function') {
  2889. // @ts-ignore
  2890. window.parent.setIsResultArray(isResultArray.value)
  2891. }
  2892. sendMessage({
  2893. type: 'isResultArray',
  2894. isResultArray: JSON.stringify(isResultArray.value),
  2895. courseid: props.courseid
  2896. })
  2897. }
  2898. const setCan = (Array: any[]) => {
  2899. isResultArray.value = Array
  2900. sendMessage({
  2901. type: 'isResultArray',
  2902. isResultArray: JSON.stringify(isResultArray.value),
  2903. courseid: props.courseid
  2904. })
  2905. }
  2906. const forceLogout = () => {
  2907. cleanupWebSocketConnection()
  2908. sendMessage({ type: 'logout' })
  2909. }
  2910. const forceLogout2 = () => {
  2911. logout()
  2912. }
  2913. const logout = () => {
  2914. // @ts-ignore
  2915. if (window.parent && typeof window.parent.topU.U.MD.U.LO.logoutSystemQ === 'function') {
  2916. // @ts-ignore
  2917. window.parent.topU.U.MD.U.LO.logoutSystemQ()
  2918. }
  2919. }
  2920. // 检查是否为创建人
  2921. const checkIsCreator = () => {
  2922. // 这里可以根据实际业务逻辑判断是否为创建人
  2923. // 比如通过props中的userid与课程创建者ID比较
  2924. if (courseDetail.value && props.userid) {
  2925. isCreator.value = courseDetail.value.userid === props.userid
  2926. }
  2927. }
  2928. /**
  2929. * 初始化消息监听
  2930. */
  2931. const messageInit = () => {
  2932. const doc = docSocket.value
  2933. if (!doc) return
  2934. // ★ 关键:判断当前绑定的共享类型是否属于这个 doc
  2935. // y-websocket 内部重连复用同一个 doc → observe 仍有效,直接返回(避免重复 observe)
  2936. // 只有 doc 被销毁重建(full reconnect)时才全部重新绑定
  2937. const boundDoc = (yMessage.value as any)?.doc
  2938. console.log('🔗 messageInit: doc.guid=', doc.guid, 'boundDoc=', boundDoc?.guid, 'same=', boundDoc === doc)
  2939. if (boundDoc === doc) {
  2940. // 同 doc 重连:补发上线消息即可
  2941. if (props.type === '2' && opRes.value.length === 0) {
  2942. sendMessage({ type: 'class_begin', courseid: props.courseid })
  2943. }
  2944. return
  2945. }
  2946. console.log('🔗 检测到新 Y.Doc,重新绑定所有共享数据监听')
  2947. // ★ 先把旧 doc 上的引用全部置空,杜绝守卫误判指向旧 doc
  2948. yMessage.value = null
  2949. yTimerState.value = null
  2950. yLaserState.value = null
  2951. yWritingBoardState.value = null
  2952. yTimerMessages.value = null
  2953. yLaserMessages.value = null
  2954. yWritingBoardMessages.value = null
  2955. yIsResultArrayMessages.value = null
  2956. // 普通消息(Map,只保留最后一条)
  2957. // 必须使用 messageV3:服务器上 messageV2 累积了旧的 delete('latest') 标记,
  2958. // 导致 get('latest') 永远返回 undefined(Yjs 的 typeMapGet 在最后一个 item 被 deleted 时返回 undefined)
  2959. yMessage.value = doc.getMap('messageV3')
  2960. yMessage.value.observe((e: any) => {
  2961. // 同时兼容 keysChanged 和 changes.keys(不同 Yjs 版本/事件结构)
  2962. const changed = e.keysChanged || e.changes?.keys
  2963. const keysMap = e.keys || e.changes?.keys
  2964. if (keysMap && keysMap.get) {
  2965. for (const [key, info] of keysMap.entries()) {
  2966. console.log(`🔗 observe key="${key}" action=${info.action} oldValue=`, info.oldValue)
  2967. }
  2968. }
  2969. console.log('🔗 yMessage observe 触发, changed keys:', changed ? Array.from(changed) : 'null')
  2970. if (!changed) return
  2971. // slideIndex 独立通道
  2972. if (changed.has('slideIndex')) {
  2973. const slideMsg = yMessage.value!.get('slideIndex')
  2974. console.log('🔗 yMessage slideIndex:', slideMsg, '当前 mId:', mId.value)
  2975. if (slideMsg && slideMsg.mId !== mId.value) {
  2976. getMessages(slideMsg)
  2977. }
  2978. }
  2979. // 其他普通消息
  2980. if (changed.has('latest')) {
  2981. const message = yMessage.value!.get('latest')
  2982. console.log('🔗 yMessage latest:', message, '当前 mId:', mId.value)
  2983. if (message && message.mId !== mId.value) {
  2984. getMessages(message)
  2985. }
  2986. }
  2987. })
  2988. // ★ 追平:连接建立后立即读取当前 latest 和 slideIndex,
  2989. // 防止老师在学生 observe 注册之前发的消息丢失(尤其是当前所在幻灯片)
  2990. const latest = yMessage.value.get('latest')
  2991. if (latest && latest.mId !== mId.value) {
  2992. console.log('🔗 追平当前 latest 消息:', latest)
  2993. getMessages(latest)
  2994. }
  2995. const slideIdx = yMessage.value.get('slideIndex')
  2996. if (slideIdx && slideIdx.mId !== mId.value) {
  2997. console.log('🔗 追平当前 slideIndex 消息:', slideIdx)
  2998. getMessages(slideIdx)
  2999. }
  3000. // 计时器消息数组
  3001. yTimerMessages.value = doc.getArray('timerMessages')
  3002. // 初始化时检查一次是否需要清理
  3003. if (yTimerMessages.value.length > 500 && isCreator.value) {
  3004. smartCleanupMessages(yTimerMessages.value, 500, 'timer', doc)
  3005. }
  3006. yTimerMessages.value.observe((e: any) => {
  3007. if (yTimerMessages.value.length > 500 && isCreator.value) {
  3008. setTimeout(() => {
  3009. if (yTimerMessages.value && yTimerMessages.value.length > 500) {
  3010. smartCleanupMessages(yTimerMessages.value, 500, 'timer', doc)
  3011. }
  3012. }, 0)
  3013. }
  3014. e.changes.added.forEach((i: any) => {
  3015. const message = i.content.getContent()[0]
  3016. if (message.mId !== mId.value) {
  3017. getMessages(message)
  3018. }
  3019. })
  3020. })
  3021. // 激光笔消息数组
  3022. yLaserMessages.value = doc.getArray('laserMessages')
  3023. if (yLaserMessages.value.length > 500 && isCreator.value) {
  3024. smartCleanupMessages(yLaserMessages.value, 500, 'laser', doc)
  3025. }
  3026. yLaserMessages.value.observe((e: any) => {
  3027. if (yLaserMessages.value.length > 500 && isCreator.value) {
  3028. setTimeout(() => {
  3029. if (yLaserMessages.value && yLaserMessages.value.length > 500) {
  3030. smartCleanupMessages(yLaserMessages.value, 500, 'laser', doc)
  3031. }
  3032. }, 0)
  3033. }
  3034. e.changes.added.forEach((i: any) => {
  3035. const message = i.content.getContent()[0]
  3036. // 只处理开关消息,位置消息直接通过 Map 同步
  3037. if (message.type === 'laser_toggle' && message.mId !== mId.value) {
  3038. getMessages(message)
  3039. }
  3040. })
  3041. })
  3042. // 画图消息数组
  3043. yWritingBoardMessages.value = doc.getArray('writingBoardMessages')
  3044. if (yWritingBoardMessages.value.length > 500 && isCreator.value) {
  3045. smartCleanupMessages(yWritingBoardMessages.value, 500, 'writingBoard', doc)
  3046. }
  3047. yWritingBoardMessages.value.observe((e: any) => {
  3048. if (yWritingBoardMessages.value.length > 500 && isCreator.value) {
  3049. setTimeout(() => {
  3050. if (yWritingBoardMessages.value && yWritingBoardMessages.value.length > 500) {
  3051. smartCleanupMessages(yWritingBoardMessages.value, 500, 'writingBoard', doc)
  3052. }
  3053. }, 0)
  3054. }
  3055. e.changes.added.forEach((i: any) => {
  3056. const message = i.content.getContent()[0]
  3057. if (message.mId !== mId.value) {
  3058. getMessages(message)
  3059. }
  3060. })
  3061. })
  3062. // isResultArray 消息数组
  3063. yIsResultArrayMessages.value = doc.getArray('isResultArrayMessages')
  3064. if (yIsResultArrayMessages.value.length > 1 && isCreator.value) {
  3065. smartCleanupMessages(yIsResultArrayMessages.value, 1, 'isResultArray', doc)
  3066. }
  3067. yIsResultArrayMessages.value.observe((e: any) => {
  3068. if (yIsResultArrayMessages.value.length > 1 && isCreator.value) {
  3069. setTimeout(() => {
  3070. if (yIsResultArrayMessages.value && yIsResultArrayMessages.value.length > 1) {
  3071. smartCleanupMessages(yIsResultArrayMessages.value, 1, 'isResultArray', doc)
  3072. }
  3073. }, 0)
  3074. }
  3075. e.changes.added.forEach((i: any) => {
  3076. const message = i.content.getContent()[0]
  3077. if (message.mId !== mId.value) {
  3078. getMessages(message)
  3079. }
  3080. })
  3081. })
  3082. // 如果是首次进入且是创建者,清空所有同步状态
  3083. if (isFirstEnter.value && isCreator.value && docSocket.value) {
  3084. console.log('🧹 首次进入且为创建者,清空所有同步状态')
  3085. docSocket.value.transact(() => {
  3086. // 清空 latest 消息(创建者进页面时清掉旧消息)
  3087. if (yMessage.value) {
  3088. yMessage.value.set('latest', null)
  3089. yMessage.value.set('slideIndex', null)
  3090. }
  3091. // 清空计时器消息数组
  3092. const timerMessagesArray = docSocket.value?.getArray?.('timerMessages')
  3093. if (timerMessagesArray) {
  3094. timerMessagesArray.delete(0, timerMessagesArray.length)
  3095. }
  3096. // 清空激光笔消息数组
  3097. const laserMessagesArray = docSocket.value?.getArray?.('laserMessages')
  3098. if (laserMessagesArray) {
  3099. laserMessagesArray.delete(0, laserMessagesArray.length)
  3100. }
  3101. // 清空画图消息数组
  3102. const writingBoardMessagesArray = docSocket.value?.getArray?.('writingBoardMessages')
  3103. if (writingBoardMessagesArray) {
  3104. writingBoardMessagesArray.delete(0, writingBoardMessagesArray.length)
  3105. }
  3106. // 清空计时器状态
  3107. const timerStateMap = docSocket.value?.getMap?.('timerState')
  3108. if (timerStateMap) {
  3109. timerStateMap.clear()
  3110. }
  3111. // 清空激光笔状态
  3112. const laserStateMap = docSocket.value?.getMap?.('laserState')
  3113. if (laserStateMap) {
  3114. laserStateMap.clear()
  3115. }
  3116. // 清空画图状态
  3117. const writingBoardStateMap = docSocket.value?.getMap?.('writingBoardState')
  3118. if (writingBoardStateMap) {
  3119. writingBoardStateMap.clear()
  3120. }
  3121. })
  3122. // 标记已不再是首次进入
  3123. isFirstEnter.value = false
  3124. }
  3125. // 计时器状态 Map 并监听
  3126. yTimerState.value = doc.getMap('timerState')
  3127. // 初始状态同步(后加入用户会立即拿到当前 map 值)
  3128. applyTimerStateSnapshot(yTimerState.value.toJSON())
  3129. yTimerState.value.observe(() => {
  3130. applyTimerStateSnapshot(yTimerState.value!.toJSON())
  3131. })
  3132. // 激光笔状态 Map 并监听
  3133. yLaserState.value = doc.getMap('laserState')
  3134. applyLaserStateSnapshot(yLaserState.value.toJSON())
  3135. yLaserState.value.observe(() => {
  3136. applyLaserStateSnapshot(yLaserState.value!.toJSON())
  3137. })
  3138. // 画图状态 Map 并监听
  3139. yWritingBoardState.value = doc.getMap('writingBoardState')
  3140. const wsnap = yWritingBoardState.value.toJSON()
  3141. console.log('📝 初始化画图状态Map,快照:', wsnap, '当前幻灯片:', currentSlide.value?.id)
  3142. nextTick(() => {
  3143. if (currentSlide.value && currentSlide.value.id) {
  3144. applyWritingBoardStateSnapshot(wsnap)
  3145. }
  3146. else {
  3147. let timeoutId: any = null
  3148. const unwatch = watch(() => currentSlide.value?.id, (slideId) => {
  3149. if (slideId) {
  3150. applyWritingBoardStateSnapshot(wsnap)
  3151. unwatch()
  3152. if (timeoutId) clearTimeout(timeoutId)
  3153. }
  3154. }, { immediate: true })
  3155. timeoutId = setTimeout(() => {
  3156. if (currentSlide.value && currentSlide.value.id) {
  3157. applyWritingBoardStateSnapshot(wsnap)
  3158. }
  3159. unwatch()
  3160. }, 3000)
  3161. }
  3162. })
  3163. yWritingBoardState.value.observe(() => {
  3164. const s = yWritingBoardState.value!.toJSON()
  3165. if (currentSlide.value && currentSlide.value.id) {
  3166. applyWritingBoardStateSnapshot(s)
  3167. }
  3168. })
  3169. // 新 doc 绑定完成,补发上线消息
  3170. if (props.type === '2' && opRes.value.length === 0) {
  3171. sendMessage({ type: 'class_begin', courseid: props.courseid })
  3172. }
  3173. }
  3174. /**
  3175. * 判断是否为特殊类型的消息(计时器、激光笔、画图)
  3176. * 注意:laser_move 不通过消息数组,直接通过 Map 同步,所以不包含在这里
  3177. */
  3178. const isSpecialMessageType = (type: string): boolean => {
  3179. const timerTypes = ['timer_start', 'timer_pause', 'timer_reset', 'timer_stop', 'timer_finish', 'timer_update']
  3180. const laserTypes = ['laser_toggle'] // laser_move 直接通过 Map,不通过消息数组
  3181. const writingBoardTypes = ['writing_board_update', 'writing_board_close', 'writing_board_blackboard']
  3182. const isResultArrayTypes = ['isResultArray']
  3183. return timerTypes.includes(type) || laserTypes.includes(type) || writingBoardTypes.includes(type) || isResultArrayTypes.includes(type)
  3184. }
  3185. /**
  3186. * 判断是否为开关类型的消息(需要保留的状态消息)
  3187. */
  3188. const isToggleMessageType = (type: string, category: 'timer' | 'laser' | 'writingBoard' | 'isResultArray'): boolean => {
  3189. if (category === 'laser') {
  3190. return type === 'laser_toggle'
  3191. }
  3192. if (category === 'writingBoard') {
  3193. return type === 'writing_board_close'
  3194. }
  3195. if (category === 'timer') {
  3196. return ['timer_start', 'timer_stop', 'timer_reset'].includes(type)
  3197. }
  3198. if (category === 'isResultArray') {
  3199. return ['isResultArray'].includes(type)
  3200. }
  3201. return false
  3202. }
  3203. /**
  3204. * 智能清理消息数组,保留最新的开关消息
  3205. */
  3206. const smartCleanupMessages = (messageArray: any, maxLength: number, category: 'timer' | 'laser' | 'writingBoard' | 'isResultArray', docSocket: Y.Doc) => {
  3207. if (!messageArray || messageArray.length <= maxLength) return
  3208. const allMessages = messageArray.toArray()
  3209. // 找到所有开关类型的消息及其索引
  3210. const toggleMessages: Array<{ index: number; message: any }> = []
  3211. for (let i = 0; i < allMessages.length; i++) {
  3212. const msg = allMessages[i]
  3213. if (msg && typeof msg === 'object' && msg.type && isToggleMessageType(msg.type, category)) {
  3214. toggleMessages.push({ index: i, message: msg })
  3215. }
  3216. }
  3217. // 如果有关键的开关消息,需要确保它们被保留
  3218. if (toggleMessages.length > 0) {
  3219. // 找到最新的开关消息索引
  3220. const latestToggleIndex = toggleMessages[toggleMessages.length - 1].index
  3221. // 如果最新的开关消息在最后500条内,直接保留最后500条
  3222. if (latestToggleIndex >= allMessages.length - maxLength) {
  3223. const excessCount = allMessages.length - maxLength
  3224. docSocket.transact(() => {
  3225. messageArray.delete(0, excessCount)
  3226. })
  3227. console.log(`🧹 清理了 ${excessCount} 条${category}消息,保留最新${maxLength}条(包含最新开关状态)`)
  3228. }
  3229. else {
  3230. // 如果最新的开关消息不在最后500条内,需要特殊处理
  3231. // 保留从最新开关消息开始到末尾的所有消息
  3232. const keepFromIndex = Math.max(0, latestToggleIndex)
  3233. const excessCount = keepFromIndex
  3234. docSocket.transact(() => {
  3235. messageArray.delete(0, excessCount)
  3236. })
  3237. console.log(`🧹 清理了 ${excessCount} 条${category}消息,保留从最新开关状态开始的所有消息`)
  3238. }
  3239. }
  3240. else {
  3241. // 没有开关消息,直接保留最后500条
  3242. const excessCount = allMessages.length - maxLength
  3243. docSocket.transact(() => {
  3244. messageArray.delete(0, excessCount)
  3245. })
  3246. console.log(`🧹 清理了 ${excessCount} 条${category}消息,保留最新${maxLength}条`)
  3247. }
  3248. }
  3249. /**
  3250. * 获取消息类型对应的数组
  3251. * 注意:laser_move 不通过消息数组,直接通过 Map 同步
  3252. */
  3253. const getMessageArrayByType = (type: string): any | null => {
  3254. const timerTypes = ['timer_start', 'timer_pause', 'timer_reset', 'timer_stop', 'timer_finish', 'timer_update']
  3255. const laserTypes = ['laser_toggle'] // laser_move 直接通过 Map,不通过消息数组
  3256. const writingBoardTypes = ['writing_board_update', 'writing_board_close', 'writing_board_blackboard']
  3257. const isResultArrayTypes = ['isResultArray']
  3258. if (timerTypes.includes(type)) {
  3259. return yTimerMessages.value
  3260. }
  3261. if (laserTypes.includes(type)) {
  3262. return yLaserMessages.value
  3263. }
  3264. if (writingBoardTypes.includes(type)) {
  3265. return yWritingBoardMessages.value
  3266. }
  3267. if (isResultArrayTypes.includes(type)) {
  3268. return yIsResultArrayMessages.value
  3269. }
  3270. return null
  3271. }
  3272. /**
  3273. * 发送消息
  3274. */
  3275. const sendMessage = (obj: any) => {
  3276. if (!docSocket.value) return
  3277. const message = obj
  3278. message.timestamp = new Date().toISOString()
  3279. message.mId = mId.value
  3280. const messageType = message.type
  3281. // laser_move 消息直接通过 Map 同步,不通过消息数组(减少延迟)
  3282. if (messageType === 'laser_move') {
  3283. if (yLaserState.value) {
  3284. docSocket.value.transact(() => {
  3285. yLaserState.value.set('x', message.x)
  3286. yLaserState.value.set('y', message.y)
  3287. })
  3288. }
  3289. return // 不存储到消息数组
  3290. }
  3291. const isSpecial = isSpecialMessageType(messageType)
  3292. docSocket.value.transact(() => {
  3293. if (isSpecial) {
  3294. // 特殊类型消息:存储到对应的独立数组
  3295. const targetArray = getMessageArrayByType(messageType)
  3296. if (targetArray) {
  3297. // 限制特殊消息数组最多 200 条,超出时删除最早的
  3298. const MAX_SPECIAL = 200
  3299. if (targetArray.length >= MAX_SPECIAL) {
  3300. targetArray.delete(0, targetArray.length - MAX_SPECIAL + 1)
  3301. }
  3302. targetArray.push([message])
  3303. }
  3304. }
  3305. else {
  3306. // 普通消息:只保留最后一条
  3307. if (yMessage.value) {
  3308. if (messageType === 'slideIndex') {
  3309. // slideIndex 单独通道,防止被其他消息挤掉
  3310. yMessage.value.set('slideIndex', message)
  3311. }
  3312. else {
  3313. yMessage.value.set('latest', message)
  3314. }
  3315. }
  3316. else {
  3317. console.warn('⚠️ sendMessage: yMessage.value 为 null,消息未写入! type:', messageType, 'docSocket:', !!docSocket.value)
  3318. }
  3319. }
  3320. })
  3321. }
  3322. const is_cast_screen = ref(false)
  3323. /**
  3324. * 处理收到的消息
  3325. */
  3326. const getMessages = (msgObj: any) => {
  3327. console.log('message', msgObj)
  3328. // 处理幻灯片切换消息
  3329. if (props.type == '2' && msgObj.type === 'slideIndex') {
  3330. goToSlide(msgObj.slideIndex)
  3331. }
  3332. // 处理跟随模式状态变化
  3333. if (props.type == '2' && msgObj.type === 'sopen') {
  3334. selectCourseSLook()
  3335. }
  3336. if (props.type == '2' && msgObj.type === 'logout') {
  3337. logout()
  3338. }
  3339. // 处理作业提交消息 - 当有人提交作业时,重新获取作业数据
  3340. if (props.type == '1' && msgObj.type === 'homework_submitted' && msgObj.courseid === props.courseid) {
  3341. console.log('收到作业提交消息,重新获取作业数据')
  3342. // 延迟一点时间,确保后端数据已更新
  3343. setTimeout(() => {
  3344. if (currentSlideHasIframe.value) {
  3345. getWork(true) // 传入true表示是更新模式
  3346. }
  3347. }, 1000)
  3348. }
  3349. // 处理点赞消息 - 当有人点赞时,重新获取点赞数据
  3350. if (msgObj.type === 'like_updated' && msgObj.courseid === props.courseid) {
  3351. console.log('收到点赞消息,重新获取点赞数据')
  3352. // 延迟一点时间,确保后端数据已更新
  3353. setTimeout(() => {
  3354. if (currentSlideHasIframe.value) {
  3355. getWork(true) // 传入true表示是更新模式
  3356. }
  3357. }, 1000)
  3358. }
  3359. // 处理英语口语状态更新 - 学生开始/完成对话时,刷新班级答题面板
  3360. if (props.type == '1' && msgObj.type === 'speaking_session_updated' && msgObj.courseid === props.courseid) {
  3361. console.log('收到英语口语状态更新,触发面板刷新')
  3362. speakingPanelRef.value?.scheduleRefetch?.()
  3363. articleReadingPanelRef.value?.scheduleRefetch?.()
  3364. }
  3365. // 计时器消息 - 学生与老师端实时显示
  3366. if (msgObj.type === 'timer_start' && msgObj.courseid === props.courseid) {
  3367. applyTimerStart(JSON.parse(msgObj.payload))
  3368. }
  3369. if (msgObj.type === 'timer_pause' && msgObj.courseid === props.courseid) {
  3370. applyTimerPause()
  3371. }
  3372. if (msgObj.type === 'timer_reset' && msgObj.courseid === props.courseid) {
  3373. applyTimerReset()
  3374. }
  3375. if (msgObj.type === 'timer_stop' && msgObj.courseid === props.courseid) {
  3376. applyTimerStop()
  3377. }
  3378. if (msgObj.type === 'timer_finish' && msgObj.courseid === props.courseid) {
  3379. applyTimerFinish()
  3380. }
  3381. if (msgObj.type === 'timer_update' && msgObj.courseid === props.courseid) {
  3382. applyTimerUpdate(msgObj.payload)
  3383. }
  3384. // 激光笔:老师广播的开关
  3385. if (props.type == '2' && msgObj.type === 'laser_toggle' && msgObj.courseid === props.courseid) {
  3386. laserPenOverlay.value.visible = !!msgObj.enabled
  3387. // 开关时立即刷新一次位置
  3388. if (laserPenOverlay.value.visible) {
  3389. refreshLaserOverlayRect()
  3390. if (laserMoveRafId) cancelAnimationFrame(laserMoveRafId)
  3391. laserMoveRafId = requestAnimationFrame(updateLaserDotPosition)
  3392. }
  3393. }
  3394. // 注意:laser_move 现在直接通过 Map 同步,不通过消息数组,所以这里不需要处理
  3395. // 画图:老师广播的画图数据
  3396. if (props.type == '2' && msgObj.type === 'writing_board_update' && msgObj.courseid === props.courseid) {
  3397. console.log('📝 学生端收到画图更新消息:', { slideId: msgObj.slideId, currentSlideId: currentSlide.value?.id, hasData: !!msgObj.dataURL })
  3398. if (currentSlide.value && msgObj.slideId === currentSlide.value.id) {
  3399. writingBoardSyncDataURL.value = msgObj.dataURL || null
  3400. // 如果消息中包含小黑板状态,也更新
  3401. if (msgObj.blackboard !== undefined) {
  3402. writingBoardSyncBlackboard.value = msgObj.blackboard
  3403. }
  3404. console.log('📝 画图数据匹配当前幻灯片,显示画图工具')
  3405. // 同步到共享 Map
  3406. if (yWritingBoardState.value) {
  3407. docSocket.value?.transact(() => {
  3408. yWritingBoardState.value.set('slideId', msgObj.slideId)
  3409. yWritingBoardState.value.set('dataURL', msgObj.dataURL)
  3410. if (msgObj.blackboard !== undefined) {
  3411. yWritingBoardState.value.set('blackboard', msgObj.blackboard)
  3412. }
  3413. })
  3414. }
  3415. }
  3416. else {
  3417. // 不是当前幻灯片,但也要更新到 Map(供后续切换时使用)
  3418. if (yWritingBoardState.value) {
  3419. docSocket.value?.transact(() => {
  3420. yWritingBoardState.value.set('slideId', msgObj.slideId)
  3421. yWritingBoardState.value.set('dataURL', msgObj.dataURL)
  3422. if (msgObj.blackboard !== undefined) {
  3423. yWritingBoardState.value.set('blackboard', msgObj.blackboard)
  3424. }
  3425. })
  3426. }
  3427. console.log('📝 画图数据不匹配当前幻灯片,已保存到Map供后续使用')
  3428. }
  3429. }
  3430. // 画图:老师关闭画图工具
  3431. if (props.type == '2' && msgObj.type === 'writing_board_close' && msgObj.courseid === props.courseid) {
  3432. writingBoardSyncDataURL.value = null
  3433. writingBoardSyncBlackboard.value = null
  3434. // 清空共享 Map
  3435. if (yWritingBoardState.value) {
  3436. docSocket.value?.transact(() => {
  3437. yWritingBoardState.value.clear()
  3438. })
  3439. }
  3440. }
  3441. // 画图:老师切换小黑板状态
  3442. if (props.type == '2' && msgObj.type === 'writing_board_blackboard' && msgObj.courseid === props.courseid) {
  3443. writingBoardSyncBlackboard.value = msgObj.blackboard || false
  3444. // 同步到共享 Map
  3445. if (yWritingBoardState.value) {
  3446. docSocket.value?.transact(() => {
  3447. yWritingBoardState.value.set('blackboard', msgObj.blackboard)
  3448. })
  3449. }
  3450. }
  3451. // 获取是否展开结果数组
  3452. if (props.type == '2' && msgObj.type === 'isResultArray' && msgObj.courseid === props.courseid) {
  3453. try {
  3454. console.error('是否展开结果数组:', msgObj.isResultArray || '[]')
  3455. const newResultArray = JSON.parse(msgObj.isResultArray || '[]')
  3456. // 值未变化时跳过下游逻辑
  3457. if (JSON.stringify(newResultArray) === JSON.stringify(isResultArray.value)) return
  3458. isResultArray.value = newResultArray
  3459. }
  3460. catch (error) {
  3461. console.error('解析是否展开结果数组失败:', error)
  3462. isResultArray.value = []
  3463. }
  3464. if (isResultArray.value.length > 0 ) {
  3465. const result = isResultArray.value[slideIndex.value]
  3466. console.log('是否展开结果数组:', result)
  3467. if (!result.can && choiceQuestionDetailDialogOpenList.value.includes(slideIndex.value)) {
  3468. openChoiceQuestionDetail2(slideIndex.value)
  3469. }
  3470. else {
  3471. getWork(true)
  3472. }
  3473. }
  3474. }
  3475. // 投屏
  3476. if (props.type == '2' && msgObj.type === 'cast_screen' && msgObj.courseid === props.courseid) {
  3477. if (is_cast_screen.value) return // 已在投屏中,忽略重复消息
  3478. openChoiceQuestionDetail3(slideIndex.value)
  3479. setTimeout(() => {
  3480. is_cast_screen.value = true
  3481. choiceQuestionDetailDialogRef.value?.castScreen?.(msgObj.workerData)
  3482. }, 500)
  3483. }
  3484. // 退出投屏
  3485. if (props.type == '2' && msgObj.type === 'exit_cast_screen' && msgObj.courseid === props.courseid) {
  3486. if (!is_cast_screen.value) return // 未在投屏中,忽略重复退出消息
  3487. openChoiceQuestionDetail3(slideIndex.value)
  3488. setTimeout(() => {
  3489. is_cast_screen.value = false
  3490. choiceQuestionDetailDialogRef.value?.exitCastScreen?.()
  3491. }, 500)
  3492. }
  3493. if (opRes.value && opRes.value.length === 0 && msgObj.type === 'class_begin' && isCreator.value && props.cid) {
  3494. console.log('操作记录:', opRes.value)
  3495. api.addPPTOp({
  3496. id: props.courseid + '-' + props.cid,
  3497. type: '1',
  3498. index: 0,
  3499. data: new Date().toISOString()
  3500. }).then(() => {
  3501. const opRes1 = api.selectPPTOp({
  3502. id: props.courseid + '-' + props.cid,
  3503. type: '1',
  3504. index: 0
  3505. }).then(res => {
  3506. console.log('操作记录:', res)
  3507. opRes.value = res[0]
  3508. console.log('操作记录:', opRes.value)
  3509. })
  3510. })
  3511. }
  3512. // ★ 老师收到学生 class_begin 后,回发当前幻灯片,确保学生有 latest 可跟随
  3513. if (msgObj.type === 'class_begin' && isCreator.value) {
  3514. const curIndex = slidesStore.slideIndex ?? 0
  3515. sendMessage({ slideIndex: curIndex, courseid: props.courseid, type: 'slideIndex' })
  3516. console.log('🔗 老师响应 class_begin,回发 slideIndex:', curIndex)
  3517. }
  3518. }
  3519. // 打开作业查看详细
  3520. const openChoiceQuestionDetail = (index:number) => {
  3521. if (!choiceQuestionDetailDialogOpenList.value.includes(index)) {
  3522. choiceQuestionDetailDialogOpenList.value.push(index)
  3523. }
  3524. else {
  3525. choiceQuestionDetailDialogOpenList.value = choiceQuestionDetailDialogOpenList.value.filter(i => i !== index)
  3526. }
  3527. }
  3528. // 打开作业查看详细
  3529. const openChoiceQuestionDetail2 = (index:number) => {
  3530. if (!choiceQuestionDetailDialogOpenList.value.includes(index)) {
  3531. // choiceQuestionDetailDialogOpenList.value.push(index)
  3532. }
  3533. else {
  3534. choiceQuestionDetailDialogOpenList.value = choiceQuestionDetailDialogOpenList.value.filter(i => i !== index)
  3535. }
  3536. }
  3537. // 打开作业查看详细
  3538. const openChoiceQuestionDetail3 = (index:number) => {
  3539. if (!choiceQuestionDetailDialogOpenList.value.includes(index)) {
  3540. choiceQuestionDetailDialogOpenList.value.push(index)
  3541. }
  3542. }
  3543. const handlePageUnload = () => {
  3544. if (isCreator.value && timerIndicator.value.visible && props.type === '1') {
  3545. sendMessage({ type: 'timer_stop', courseid: props.courseid })
  3546. }
  3547. // 创建老师刷新/关闭页面时,清空所有同步状态
  3548. if (isCreator.value && props.type === '1') {
  3549. clearAllSyncStates()
  3550. }
  3551. // 清理画图延迟发送定时器
  3552. if (drawingDelayTimer.value) {
  3553. clearTimeout(drawingDelayTimer.value)
  3554. drawingDelayTimer.value = null
  3555. }
  3556. }
  3557. // 检测浏览器类型
  3558. const detectBrowser = () => {
  3559. const ua = navigator.userAgent
  3560. // 按优先级顺序检测
  3561. if (ua.includes('Edg/') || ua.includes('Edge/')) {
  3562. return 'Microsoft Edge'
  3563. }
  3564. if (ua.includes('Firefox')) {
  3565. return 'Mozilla Firefox'
  3566. }
  3567. if (ua.includes('Trident') || ua.includes('MSIE')) {
  3568. return 'Internet Explorer'
  3569. }
  3570. if (ua.includes('360EE')) {
  3571. return '360 Browser (极速模式)'
  3572. }
  3573. if (ua.includes('360SE')) {
  3574. return '360 Browser (安全模式)'
  3575. }
  3576. if (ua.includes('SLBrowser')) {
  3577. return 'QQ Browser'
  3578. }
  3579. if (ua.includes('UCBrowser')) {
  3580. return 'UC Browser'
  3581. }
  3582. if (ua.includes('Opera') || ua.includes('OPR/')) {
  3583. return 'Opera'
  3584. }
  3585. if (ua.includes('Chrome') && !ua.includes('Edg/')) {
  3586. return 'Google Chrome'
  3587. }
  3588. if (ua.includes('Safari/') && !ua.includes('Chrome')) {
  3589. return 'Safari'
  3590. }
  3591. return 'Other Browser'
  3592. }
  3593. // 用户数据上报功能
  3594. const addOp3 = async (userTime: any, loadTime: any, object: any, status: any) => {
  3595. if (!props.userid) return
  3596. try {
  3597. if (!userJson.value || !userJson.value.accountNumber) {
  3598. const res = await axios.get('https://pbl.cocorobo.cn/api/pbl/selectUser2', {
  3599. params: { userid: props.userid }
  3600. })
  3601. if (res == 201 || res.length == 0) {
  3602. // message.error('登录已过期,请重新登录')
  3603. return
  3604. }
  3605. userJson.value = res[0][0]
  3606. console.log(userJson.value)
  3607. console.log(res[0][0])
  3608. }
  3609. }
  3610. catch (e) {
  3611. console.log(e)
  3612. if (e === 123) {
  3613. return
  3614. }
  3615. setTimeout(() => {
  3616. addOp3(userTime, loadTime, object, status)
  3617. }, 10000)
  3618. return
  3619. }
  3620. const _time = new Date()
  3621. .toLocaleString('zh-CN', { hour12: false, timeZone: 'Asia/Shanghai' })
  3622. .replace(/\//g, '-')
  3623. const browser = detectBrowser()
  3624. const params = {
  3625. userid: props.userid,
  3626. username: userJson.value.username,
  3627. accountNumber: userJson.value.accountNumber,
  3628. org: userJson.value.orgName,
  3629. school: userJson.value.schoolName,
  3630. role: userJson.value.type == '1' ? '老师' : '学生',
  3631. browser,
  3632. userTime: userTime == '1' ? _time : userTime, // 使用时间 1次的就1 其次传秒
  3633. loadTime, // load的时间没有就''
  3634. object: JSON.stringify(object), // 执行信息传json
  3635. status // 成功返回success。失败返回error的信息
  3636. }
  3637. console.log('params', params)
  3638. axios
  3639. .post('https://pbl.cocorobo.cn/api/mongo/updateUserData2', [params])
  3640. .then(res => {
  3641. if (res.status === 1) {
  3642. console.log('保存成功')
  3643. }
  3644. else {
  3645. console.log('保存失败')
  3646. }
  3647. })
  3648. .catch(e => {
  3649. console.log('保存失败')
  3650. console.log(e)
  3651. })
  3652. }
  3653. onMounted(() => {
  3654. document.addEventListener('keydown', handleKeydown)
  3655. // 处理URL参数
  3656. if (props.courseid || props.type) {
  3657. console.log('收到URL参数:', { courseid: props.courseid, type: props.type })
  3658. // 这里可以根据courseid和type进行相应的处理
  3659. // 比如加载特定的课程数据、设置特定的显示模式等
  3660. if (props.courseid) {
  3661. console.log('课程ID:', props.courseid)
  3662. // TODO: 根据courseid加载对应的课程数据
  3663. }
  3664. if (props.type) {
  3665. console.log('类型:', props.type)
  3666. // TODO: 根据type设置特定的显示模式或功能
  3667. }
  3668. }
  3669. getCourseDetail()
  3670. // 计算初始缩放比例
  3671. nextTick(() => {
  3672. calculateScale()
  3673. // 处理iframe链接
  3674. processIframeLinks()
  3675. // 初始化时检查并自动切换到可用面板
  3676. autoSwitchToAvailablePanel()
  3677. })
  3678. // 监听窗口大小变化
  3679. window.addEventListener('resize', calculateScale)
  3680. // 监听全屏状态变化
  3681. document.addEventListener('fullscreenchange', handleFullscreenChange)
  3682. // 监听幻灯片数据更新事件(来自useImport的readJSON)
  3683. window.addEventListener('slidesDataUpdated', handleSlidesDataUpdated)
  3684. // 监听视口尺寸更新事件
  3685. window.addEventListener('viewportSizeUpdated', handleViewportSizeUpdated)
  3686. // 将导入导出功能暴露到window上,方便调试和外部调用
  3687. ; (window as any).PPTistStudent = {
  3688. importJSON,
  3689. exportJSON,
  3690. slides: slidesStore.slides,
  3691. currentSlide: computed(() => slidesStore.currentSlide),
  3692. slideIndex: computed(() => slidesStore.slideIndex),
  3693. goToSlide,
  3694. previousSlide,
  3695. nextSlide,
  3696. enterFullscreen,
  3697. toggleLaserPen,
  3698. // 添加URL参数到全局对象中
  3699. courseid: props.courseid,
  3700. type: props.type,
  3701. successSubmit,
  3702. toggleFollowMode,
  3703. // 添加重连功能
  3704. manualReconnect,
  3705. connectionStatus: computed(() => connectionStatus.value),
  3706. forceLogout,
  3707. forceLogout2,
  3708. setCan,
  3709. // Yjs 诊断函数:控制台调用 PPTistStudent.diagnoseYjs()
  3710. diagnoseYjs: () => {
  3711. const doc = docSocket.value
  3712. if (!doc) {
  3713. console.log('════════ Yjs 诊断 ════════\ndocSocket.value 为 null')
  3714. return null
  3715. }
  3716. const msgV3Type = doc.share.get('messageV3')
  3717. const oldMsgType = doc.share.get('message')
  3718. const report = {
  3719. '1. doc.guid': doc.guid,
  3720. '2. yMessage.value === doc.share.get("messageV3")': yMessage.value === msgV3Type,
  3721. '3. yMessage.value?.doc?.guid': yMessage.value?.doc?.guid,
  3722. '4. doc.store.clients.size': doc.store.clients.size,
  3723. '5a. share.get("messageV3") 类型': msgV3Type?.constructor?.name,
  3724. '5b. share.get("message") 类型': oldMsgType?.constructor?.name,
  3725. '6. messageV3.size': msgV3Type?.size,
  3726. '7. messageV3?.get("latest")': msgV3Type?.get?.('latest'),
  3727. '8. yMessage.value?.get("latest")': yMessage.value?.get?.('latest'),
  3728. '9. doc 里所有顶层 key': Array.from(doc.share.entries()).map(([k, v]: [string, any]) => k + ':' + v.constructor.name),
  3729. '10. provider synced': providerSocket.value?.synced,
  3730. '11. ws.readyState': providerSocket.value?.ws?.readyState,
  3731. '12. messageV3?.get("slideIndex")': msgV3Type?.get?.('slideIndex'),
  3732. }
  3733. console.log('════════ Yjs 诊断 ════════')
  3734. for (const [k, v] of Object.entries(report)) {
  3735. console.log(k + ':', typeof v === 'object' ? JSON.stringify(v) : v)
  3736. }
  3737. return report
  3738. },
  3739. }
  3740. console.log('PPTist Student View 已加载,可通过 window.PPTistStudent 访问功能')
  3741. console.log('URL参数:', { courseid: props.courseid, type: props.type })
  3742. // 初始化WebSocket连接
  3743. if (api.yweb_socket) {
  3744. createWebSocketConnection()
  3745. }
  3746. // 创建人离开页面时,广播停止计时
  3747. // beforeunload 事件(页面刷新或关闭)
  3748. // window.addEventListener('beforeunload', handlePageUnload)
  3749. // visibilitychange 事件(适用于 iframe 嵌套场景,当外层页面返回时触发)
  3750. const handleVisibilityChange = () => {
  3751. if (document.hidden && isCreator.value) {
  3752. // 页面被隐藏时,清空所有同步状态
  3753. clearAllSyncStates()
  3754. if (timerIndicator.value.visible) {
  3755. sendMessage({ type: 'timer_stop', courseid: props.courseid })
  3756. }
  3757. }
  3758. }
  3759. document.addEventListener('visibilitychange', handleVisibilityChange)
  3760. // pagehide 事件(作为补充,某些浏览器中比 beforeunload 更可靠)
  3761. window.addEventListener('pagehide', () => {
  3762. console.log('pagehide')
  3763. handlePageUnload()
  3764. })
  3765. // 存储清理函数,方便在 onUnmounted 中移除
  3766. ;(window as any).__pptistStudentUnloadHandlers = {
  3767. // beforeunload: handlePageUnload,
  3768. visibilitychange: handleVisibilityChange,
  3769. pagehide: handlePageUnload
  3770. }
  3771. })
  3772. onUnmounted(() => {
  3773. document.removeEventListener('keydown', handleKeydown)
  3774. window.removeEventListener('resize', calculateScale)
  3775. document.removeEventListener('fullscreenchange', handleFullscreenChange)
  3776. // 移除幻灯片数据更新事件监听器
  3777. window.removeEventListener('slidesDataUpdated', handleSlidesDataUpdated)
  3778. // 移除视口尺寸更新事件监听器
  3779. window.removeEventListener('viewportSizeUpdated', handleViewportSizeUpdated)
  3780. // 清理WebSocket连接
  3781. if (reconnectTimer.value) {
  3782. clearTimeout(reconnectTimer.value)
  3783. reconnectTimer.value = null
  3784. }
  3785. // 清理认证 token 更新定时器
  3786. if (authTokenUpdateTimer.value) {
  3787. clearTimeout(authTokenUpdateTimer.value)
  3788. authTokenUpdateTimer.value = null
  3789. }
  3790. // 清理心跳定时器
  3791. if (heartbeatTimer.value) {
  3792. clearInterval(heartbeatTimer.value)
  3793. heartbeatTimer.value = null
  3794. }
  3795. // 清理 socket 连接检查定时器
  3796. if (socketCheckTimer.value) {
  3797. clearInterval(socketCheckTimer.value)
  3798. socketCheckTimer.value = null
  3799. }
  3800. // if (providerSocket.value) {
  3801. // providerSocket.value.destroy()
  3802. // providerSocket.value = null
  3803. // }
  3804. // 清理画图延迟发送定时器
  3805. if (drawingDelayTimer.value) {
  3806. clearTimeout(drawingDelayTimer.value)
  3807. drawingDelayTimer.value = null
  3808. }
  3809. // 清理页面卸载相关的事件监听器
  3810. if ((window as any).__pptistStudentUnloadHandlers) {
  3811. const handlers = (window as any).__pptistStudentUnloadHandlers
  3812. // window.removeEventListener('beforeunload', handlers.beforeunload)
  3813. document.removeEventListener('visibilitychange', handlers.visibilitychange)
  3814. window.removeEventListener('pagehide', handlers.pagehide)
  3815. delete (window as any).__pptistStudentUnloadHandlers
  3816. }
  3817. // 清理window上的引用
  3818. if ((window as any).PPTistStudent) {
  3819. delete (window as any).PPTistStudent
  3820. console.log('PPTist Student View 已卸载,window.PPTistStudent 已清理')
  3821. }
  3822. if (timerInterval.value) {
  3823. clearInterval(timerInterval.value)
  3824. timerInterval.value = null
  3825. }
  3826. handlePageUnload()
  3827. })
  3828. // 获取认证 token
  3829. const getAuthToken = async (): Promise<string> => {
  3830. try {
  3831. // 使用代理路径避免跨域问题
  3832. // 开发环境:通过 vite 代理 /yjs-auth/auth/token -> https://yjsredis.cocorobo.cn/auth/token
  3833. // 生产环境:需要配置服务器代理或使用后端 API
  3834. // 兼容性修复:不直接使用 import.meta.env.DEV
  3835. let isDev = false
  3836. // 判断如果有 window 对象且以 localhost/127.0.0.1 开头,则认为是开发环境
  3837. if (typeof window !== 'undefined') {
  3838. const hostname = window.location.hostname
  3839. if (
  3840. hostname === 'localhost' ||
  3841. hostname === '127.0.0.1' ||
  3842. hostname === '::1' ||
  3843. /^192\.168\.\d+\.\d+$/.test(hostname)
  3844. ) {
  3845. isDev = true
  3846. }
  3847. }
  3848. let authUrl = ''
  3849. // if (isDev) {
  3850. // // 开发环境使用 vite 代理
  3851. // authUrl = '/yjs-auth/auth/token'
  3852. // }
  3853. // else {
  3854. // 生产环境:如果服务器有代理则使用代理,否则直接访问(需要服务器配置 CORS)
  3855. // 或者通过后端 API 获取 token
  3856. let baseUrl = 'https://yjsredis.cocorobo.cn/'
  3857. baseUrl = baseUrl.replace(/\/+$/, '')
  3858. authUrl = `${baseUrl}/auth/token`
  3859. // }
  3860. console.log('🔐 获取认证 token,URL:', authUrl)
  3861. const response = await axios.get(authUrl)
  3862. console.log('🔐 获取认证 token 成功', response)
  3863. return response
  3864. }
  3865. catch (error) {
  3866. console.error('🔐 获取认证 token 失败:', error)
  3867. throw error
  3868. }
  3869. }
  3870. // 定期更新认证 token
  3871. const updateAuthToken = async () => {
  3872. try {
  3873. if (!providerSocket.value) return
  3874. const newToken = await getAuthToken()
  3875. authToken.value = newToken
  3876. // 更新 provider 的 auth 参数
  3877. if (providerSocket.value.params) {
  3878. providerSocket.value.params.yauth = newToken
  3879. }
  3880. console.log('🔐 认证 token 已更新')
  3881. // 30分钟后再次更新
  3882. // if (authTokenUpdateTimer.value) {
  3883. // clearTimeout(authTokenUpdateTimer.value)
  3884. // }
  3885. authTokenUpdateTimer.value = setTimeout(updateAuthToken, 30 * 60 * 1000) as unknown as NodeJS.Timeout
  3886. // authTokenUpdateTimer.value = setTimeout(updateAuthToken, 10 * 1000) as unknown as NodeJS.Timeout
  3887. }
  3888. catch (error) {
  3889. console.error('🔐 更新认证 token 失败:', error)
  3890. // 失败后1秒重试
  3891. if (authTokenUpdateTimer.value) {
  3892. clearTimeout(authTokenUpdateTimer.value)
  3893. }
  3894. authTokenUpdateTimer.value = setTimeout(updateAuthToken, 10 * 1000) as unknown as NodeJS.Timeout
  3895. }
  3896. }
  3897. // 手动重连
  3898. const manualReconnect = () => {
  3899. if (isConnecting.value) return
  3900. reconnectAttempts.value = 0 // 重置重连次数
  3901. createWebSocketConnection()
  3902. }
  3903. // 清理 WebSocket 连接(提取为独立函数)
  3904. const cleanupWebSocketConnection = () => {
  3905. if (providerSocket.value) {
  3906. // 销毁连接
  3907. providerSocket.value.destroy()
  3908. providerSocket.value = null
  3909. }
  3910. if (docSocket.value) {
  3911. // 注意:doc 会被 provider.destroy() 自动销毁,不需要手动 destroy
  3912. // 但如果 provider 已经被销毁,这里置空即可
  3913. docSocket.value.destroy()
  3914. docSocket.value = null
  3915. }
  3916. // ★ 关键:doc 已销毁,必须把绑定在旧 doc 上的共享类型引用全部置空,
  3917. // 否则重连后 messadocSocket.value.guid === yMessazeInit() 的 if (!yXxx.value) 守卫会跳过绑定,
  3918. // 新 doc 收到更新时 observe 回调不会触发(表现为突然收不到消息)
  3919. yMessage.value = null
  3920. yTimerState.value = null
  3921. yLaserState.value = null
  3922. yWritingBoardState.value = null
  3923. yTimerMessages.value = null
  3924. yLaserMessages.value = null
  3925. yWritingBoardMessages.value = null
  3926. yIsResultArrayMessages.value = null
  3927. }
  3928. // 创建WebSocket连接
  3929. const createWebSocketConnection = async (type = 1) => {
  3930. if (!api.yweb_socket || isConnecting.value) return
  3931. isConnecting.value = true
  3932. connectionStatus.value = 'connecting'
  3933. try {
  3934. // 清理之前的连接
  3935. // if (providerSocket.value && type == 1) {
  3936. // providerSocket.value.destroy()
  3937. // providerSocket.value = null
  3938. // }
  3939. cleanupWebSocketConnection()
  3940. // 清理之前的 token 更新定时器
  3941. if (authTokenUpdateTimer.value) {
  3942. clearTimeout(authTokenUpdateTimer.value)
  3943. authTokenUpdateTimer.value = null
  3944. }
  3945. // 获取认证 token
  3946. try {
  3947. authToken.value = await getAuthToken()
  3948. console.log('🔐 认证 token 获取成功,准备连接 WebSocket')
  3949. }
  3950. catch (error) {
  3951. console.error('🔐 获取认证 token 失败,连接可能失败:', error)
  3952. connectionStatus.value = 'disconnected'
  3953. isConnecting.value = false
  3954. handleDisconnection()
  3955. return
  3956. }
  3957. docSocket.value = new Y.Doc()
  3958. docSocket.value.gc = true
  3959. providerSocket.value = new WebsocketProvider(
  3960. api.yweb_socket,
  3961. 'PPT' + props.courseid,
  3962. docSocket.value,
  3963. {
  3964. params: { yauth: authToken.value },
  3965. resyncInterval: 5000, // 每 5 秒用标准协议请求服务器状态(代替畸形心跳)
  3966. maxBackoffTime: 5000, // 重连最长退避 5 秒
  3967. }
  3968. )
  3969. providerSocket.value.awareness.setLocalState(null)
  3970. providerSocket.value.awareness.destroy() // 完全禁用 awareness
  3971. // ★ 三层日志之一:raw websocket 消息(确认数据到达浏览器)
  3972. const _ws = (providerSocket.value as any).ws
  3973. if (_ws && !_ws.__logged) {
  3974. _ws.__logged = true // 防止重复绑定
  3975. // 包一层 onmessage,抓 provider 处理异常
  3976. const _origOnMsg = _ws.onmessage
  3977. if (typeof _origOnMsg === 'function') {
  3978. _ws.onmessage = function(ev: MessageEvent) {
  3979. try {
  3980. _origOnMsg.call(_ws, ev)
  3981. }
  3982. catch (e: any) {
  3983. console.error('❌ provider onmessage 异常:', e?.message || e, e?.stack || '')
  3984. }
  3985. }
  3986. }
  3987. _ws.addEventListener('message', (ev: MessageEvent) => {
  3988. try {
  3989. const data = new Uint8Array(ev.data)
  3990. const msgType = data[0]
  3991. const typeNames: any = { 0: 'sync', 1: 'awareness', 2: 'queryAwareness' }
  3992. let detail = ''
  3993. if (msgType === 0) {
  3994. const sub = data[1]
  3995. detail = ({ 0: 'step1(请求缺失)', 1: 'step2(服务器推送)', 2: 'update' } as any)[sub] || 'unknown'
  3996. }
  3997. console.log(`📥 ws raw: ${typeNames[msgType] || msgType} ${detail} (${data.length} bytes)`)
  3998. // ★ 诊断:sync update 到达时手动解码 + applyUpdate,看是不是重复数据
  3999. if (msgType === 0 && data[1] === 2) {
  4000. const doc = docSocket.value
  4001. if (doc) {
  4002. // 解码 varint 提取 update bytes
  4003. let pos = 2 // 跳过 msgType + subType
  4004. let updateLen = 0
  4005. let shift = 0
  4006. while (pos < data.length) {
  4007. const b = data[pos++]
  4008. updateLen |= (b & 0x7f) << shift
  4009. if (b < 0x80) break
  4010. shift += 7
  4011. }
  4012. const updateBytes = data.slice(pos, pos + updateLen)
  4013. // ★ 用 Y.decodeUpdate 解码 update(不创建 temp doc,不触发 applyUpdate 的 DELETE)
  4014. try {
  4015. const { structs } = Y.decodeUpdate(updateBytes)
  4016. console.log(`📦 解码: updateBytes=${updateBytes.length}, structs=${structs.length}`)
  4017. for (const struct of structs) {
  4018. const arr = struct?.content?.arr
  4019. console.log(`📦 struct: type=${struct?.content?.constructor?.name}, parentSub=${struct?.parentSub}, arr=${arr ? JSON.stringify(arr)?.slice(0, 150) : '无'}`)
  4020. if (arr && Array.isArray(arr)) {
  4021. for (const val of arr) {
  4022. if (val && typeof val === 'object' && val.type && val.mId) {
  4023. console.log(`📦 ✅ 从 update 提取消息: type=${val.type}, mId=${val.mId}, 当前 mId=${mId.value}`)
  4024. if (val.mId !== mId.value) {
  4025. getMessages(val)
  4026. }
  4027. }
  4028. }
  4029. }
  4030. }
  4031. }
  4032. catch (e) {
  4033. console.log('📦 update 解码失败:', e)
  4034. }
  4035. }
  4036. }
  4037. }
  4038. catch (e) {
  4039. console.log('📥 ws raw: parse error', e)
  4040. }
  4041. })
  4042. }
  4043. // ★ 三层日志之二:Y.Doc update 事件 — 列出所有根类型的 size,看更新到底改了哪个
  4044. docSocket.value.on('update', (update: Uint8Array, origin: any) => {
  4045. // origin === providerSocket.value 表示来自网络
  4046. // origin !== providerSocket.value 表示本地修改
  4047. if (origin !== providerSocket.value) return
  4048. try {
  4049. const { structs } = Y.decodeUpdate(update)
  4050. for (const struct of structs) {
  4051. const arr = (struct as any)?.content?.arr
  4052. if (arr && Array.isArray(arr)) {
  4053. for (const val of arr) {
  4054. if (val && typeof val === 'object' && val.type && val.mId) {
  4055. console.log(`📦 提取: type=${val.type}, mId=${val.mId}`)
  4056. if (val.mId !== mId.value) getMessages(val)
  4057. }
  4058. }
  4059. }
  4060. }
  4061. }
  4062. catch (e) {
  4063. console.log('📦 解析失败:', e)
  4064. }
  4065. })
  4066. // 清理可能残留的旧心跳定时器
  4067. if (heartbeatTimer.value) {
  4068. clearInterval(heartbeatTimer.value)
  4069. heartbeatTimer.value = null
  4070. }
  4071. // 启动定期更新 token
  4072. // 30分钟后再次更新
  4073. if (authTokenUpdateTimer.value) {
  4074. clearTimeout(authTokenUpdateTimer.value)
  4075. }
  4076. authTokenUpdateTimer.value = setTimeout(updateAuthToken, 30 * 60 * 1000) as unknown as NodeJS.Timeout
  4077. // authTokenUpdateTimer.value = setTimeout(updateAuthToken, 10 * 1000) as unknown as NodeJS.Timeout
  4078. providerSocket.value.on('status', (event: any) => {
  4079. console.log('👉 WebSocket状态:', event.status)
  4080. if (event.status === 'connected') {
  4081. console.log('👉连接成功websocket(teachingMode)')
  4082. connectionStatus.value = 'connected'
  4083. isConnecting.value = false
  4084. reconnectAttempts.value = 0 // 重置重连次数
  4085. // 清理重连定时器
  4086. if (reconnectTimer.value) {
  4087. clearTimeout(reconnectTimer.value)
  4088. reconnectTimer.value = null
  4089. }
  4090. mId.value = Math.random().toString(36).substr(2, 9)
  4091. messageInit()
  4092. console.log('🔗 connected 后: yMessage.value =', yMessage.value ? '已绑定' : 'null', 'doc.guid=', docSocket.value?.guid)
  4093. // 连接成功后,读取当前计时器状态(Map)
  4094. if (docSocket.value) {
  4095. initializeYjsData()
  4096. }
  4097. // if (type == 1) {
  4098. // setTimeout(() => {
  4099. // createWebSocketConnection(2)
  4100. // }, 1000)
  4101. // }
  4102. }
  4103. else if (event.status === 'disconnected') {
  4104. console.log('👉 连接断开,等待自动重连...')
  4105. isConnecting.value = false
  4106. }
  4107. // else if (event.status === 'disconnected') {
  4108. // console.log('👉 WebSocket连接断开')
  4109. // connectionStatus.value = 'disconnected'
  4110. // isConnecting.value = false
  4111. // setTimeout(() => {
  4112. // createWebSocketConnection(2)
  4113. // }, 5000)
  4114. // }
  4115. // else if (event.status === 'closed') {
  4116. // console.log('👉 WebSocket连接断开closed')
  4117. // updateAuthToken().then(() => {
  4118. // providerSocket.value.connect() // 尝试重新连接
  4119. // })
  4120. // }
  4121. })
  4122. // ✅ 只记录日志,不干预状态
  4123. providerSocket.value.on('connection-error', (error: any) => {
  4124. console.error('👉 WebSocket 连接错误(将自动重连):', error)
  4125. })
  4126. providerSocket.value.on('connection-close', (event: any) => {
  4127. console.log('👉 WebSocket 连接关闭(将自动重连):', event)
  4128. })
  4129. // ★ synced 事件:在服务器状态同步完成(sync step 2 已应用到 Y.Doc)后触发
  4130. // 'connected' 在 onopen 时就触发,此时 sync 尚未完成,messageInit 的 catch-up 读不到数据
  4131. // 'synced' 才是做 catch-up 的正确时机——确保服务器上的 latest 已写入本地 Y.Doc
  4132. providerSocket.value.on('sync', (isSynced: boolean) => {
  4133. if (!isSynced) return
  4134. console.log('🔗 Yjs sync 完成,开始 catch-up')
  4135. // ★ 诊断:枚举 doc.share 里所有根类型,给每个都加 observe
  4136. const share = (docSocket.value as any).share
  4137. if (share) {
  4138. console.log('🔗 根类型列表:')
  4139. for (const [name, type] of share.entries()) {
  4140. console.log(` ${name}: ${type.constructor.name}, size: ${type.size ?? type.length ?? '?'}`)
  4141. // 给每个根类型加 observe,看哪个在动
  4142. if (type.observe && !type.__diagObserved) {
  4143. type.__diagObserved = true
  4144. type.observe((e: any) => {
  4145. const changed = e.keysChanged || e.changes?.keys
  4146. console.log(`🔗 [${name}] observe 触发! changed:`, changed ? Array.from(changed) : e)
  4147. })
  4148. }
  4149. }
  4150. }
  4151. // catch-up:读取服务器同步过来的 latest 和 slideIndex 消息
  4152. if (yMessage.value) {
  4153. const latest = yMessage.value.get('latest')
  4154. console.log('🔗 synced catch-up latest:', latest)
  4155. if (latest && latest.mId !== mId.value) {
  4156. console.log('🔗 synced catch-up: 处理 latest 消息', latest.type)
  4157. getMessages(latest)
  4158. }
  4159. const slideIdx = yMessage.value.get('slideIndex')
  4160. console.log('🔗 synced catch-up slideIndex:', slideIdx)
  4161. if (slideIdx && slideIdx.mId !== mId.value) {
  4162. console.log('🔗 synced catch-up: 处理 slideIndex 消息', slideIdx.slideIndex)
  4163. getMessages(slideIdx)
  4164. }
  4165. }
  4166. // catch-up:读取计时器、激光笔、画图状态
  4167. if (yTimerState.value) {
  4168. const snapshot = yTimerState.value.toJSON()
  4169. applyTimerStateSnapshot(snapshot)
  4170. }
  4171. if (yLaserState.value) {
  4172. const laserSnap = yLaserState.value.toJSON()
  4173. if (laserSnap.visible !== undefined) {
  4174. laserPenOverlay.value.visible = !!laserSnap.visible
  4175. }
  4176. }
  4177. // 学生端补发上线消息,让老师知道学生已就绪
  4178. if (props.type === '2' && opRes.value.length === 0) {
  4179. console.log('🔗 sync handler: yMessage.value =', yMessage.value ? '已绑定' : 'null', 'doc.guid=', docSocket.value?.guid)
  4180. sendMessage({ type: 'class_begin', courseid: props.courseid })
  4181. // ★ 确认 class_begin 是否真的写入了 messageV3
  4182. const msgV3 = (docSocket.value as any)?.share?.get?.('messageV3')
  4183. console.log('🔗 学生发送 class_begin 后, messageV3.size:', msgV3?.size, 'latest:', msgV3?.get?.('latest')?.type)
  4184. }
  4185. // ★ 老师端:sync 完成后补发当前幻灯片,确保 messageV3 的 latest 有值
  4186. // 解决:服务器上 latest 被 clearAllSyncStates 删除后,新连入学生拿到空 Map 无法跟随
  4187. if (props.type === '1') {
  4188. const curIndex = slidesStore.slideIndex ?? 0
  4189. sendMessage({ slideIndex: curIndex, courseid: props.courseid, type: 'slideIndex' })
  4190. console.log('🔗 老师补发当前幻灯片 slideIndex:', curIndex)
  4191. }
  4192. // 自动运行 Yjs 诊断
  4193. (window as any).PPTistStudent?.diagnoseYjs?.()
  4194. })
  4195. // 监听连接错误
  4196. // providerSocket.value.on('connection-error', (error: any) => {
  4197. // console.error('👉 WebSocket连接错误:', error)
  4198. // connectionStatus.value = 'disconnected'
  4199. // isConnecting.value = false
  4200. // setTimeout(() => {
  4201. // createWebSocketConnection(2)
  4202. // }, 5000)
  4203. // })
  4204. // 监听连接关闭
  4205. // providerSocket.value.on('connection-close', (error: any) => {
  4206. // console.error('👉 WebSocket连接关闭:', error)
  4207. // connectionStatus.value = 'disconnected'
  4208. // isConnecting.value = false
  4209. // setTimeout(() => {
  4210. // updateAuthToken().then(() => {
  4211. // providerSocket.value.connect() // 尝试重新连接
  4212. // })
  4213. // }, 5000)
  4214. // })
  4215. }
  4216. catch (error) {
  4217. console.error('👉 创建WebSocket连接失败:', error)
  4218. connectionStatus.value = 'disconnected'
  4219. isConnecting.value = false
  4220. // setTimeout(() => {
  4221. // createWebSocketConnection(2)
  4222. // }, 5000)
  4223. cleanupWebSocketConnection()
  4224. setTimeout(createWebSocketConnection, 5000)
  4225. }
  4226. // 启动 socket 连接检查定时器
  4227. // startSocketCheckTimer()
  4228. }
  4229. // ✅ 提取业务初始化逻辑
  4230. const initializeYjsData = () => {
  4231. if (!docSocket.value) return
  4232. yTimerState.value = docSocket.value.getMap('timerState')
  4233. const snapshot = yTimerState.value.toJSON()
  4234. applyTimerStateSnapshot(snapshot)
  4235. // 激光笔 map
  4236. yLaserState.value = docSocket.value.getMap('laserState')
  4237. const ls = yLaserState.value.toJSON()
  4238. applyLaserStateSnapshot(ls)
  4239. yLaserState.value.observe(() => {
  4240. const s = yLaserState.value.toJSON()
  4241. applyLaserStateSnapshot(s)
  4242. })
  4243. // 画图 map
  4244. yWritingBoardState.value = docSocket.value.getMap('writingBoardState')
  4245. const ws = yWritingBoardState.value.toJSON()
  4246. console.log('📝 WebSocket连接成功,读取画图状态:', ws, '当前幻灯片:', currentSlide.value?.id)
  4247. // 延迟应用,确保 currentSlide 已初始化
  4248. nextTick(() => {
  4249. // 如果 currentSlide 还没准备好,再等一帧
  4250. if (currentSlide.value && currentSlide.value.id) {
  4251. applyWritingBoardStateSnapshot(ws)
  4252. }
  4253. else {
  4254. // 如果还没准备好,等待 currentSlide 变化(最多等待3秒)
  4255. let timeoutId: any = null
  4256. const unwatch = watch(() => currentSlide.value?.id, (slideId) => {
  4257. if (slideId) {
  4258. applyWritingBoardStateSnapshot(ws)
  4259. unwatch()
  4260. if (timeoutId) clearTimeout(timeoutId)
  4261. }
  4262. }, { immediate: true })
  4263. // 3秒后如果还没准备好,强制应用一次
  4264. timeoutId = setTimeout(() => {
  4265. if (currentSlide.value && currentSlide.value.id) {
  4266. applyWritingBoardStateSnapshot(ws)
  4267. }
  4268. unwatch()
  4269. }, 3000)
  4270. }
  4271. })
  4272. yWritingBoardState.value.observe(() => {
  4273. const s = yWritingBoardState.value.toJSON()
  4274. if (currentSlide.value && currentSlide.value.id) {
  4275. applyWritingBoardStateSnapshot(s)
  4276. }
  4277. })
  4278. }
  4279. // 处理连接断开
  4280. const handleDisconnection = () => {
  4281. if (reconnectAttempts.value < maxReconnectAttempts.value) {
  4282. reconnectAttempts.value++
  4283. console.log(`👉 尝试重连 (${reconnectAttempts.value}/${maxReconnectAttempts.value})`)
  4284. reconnectTimer.value = setTimeout(() => {
  4285. createWebSocketConnection()
  4286. }, reconnectInterval.value) as unknown as NodeJS.Timeout
  4287. }
  4288. else {
  4289. console.error('👉 WebSocket重连次数已达上限,停止重连')
  4290. // 可以在这里显示用户提示
  4291. message.error( lang.ssNetError )
  4292. }
  4293. }
  4294. // 启动 socket 连接检查定时器
  4295. const startSocketCheckTimer = () => {
  4296. // 清理之前的定时器
  4297. if (socketCheckTimer.value) {
  4298. clearInterval(socketCheckTimer.value)
  4299. socketCheckTimer.value = null
  4300. }
  4301. // 每10秒检查一次 socket 连接状态
  4302. socketCheckTimer.value = setInterval(() => {
  4303. if (providerSocket.value) {
  4304. // 直接检查 providerSocket 的连接状态
  4305. // WebsocketProvider 有一个 connected 属性来表示连接状态
  4306. const isConnected = (providerSocket.value as any).ws.readyState
  4307. console.log('🔍 定时器检查 socket 连接状态:', isConnected)
  4308. if (isConnected !== 1) {
  4309. console.log('🔍 定时器检查发现 socket 未连接,执行重连')
  4310. createWebSocketConnection(2)
  4311. }
  4312. }
  4313. }, 10000) as unknown as NodeJS.Timeout
  4314. }
  4315. // 工具函数:格式化时间
  4316. const formatTime = (totalSec: number) => {
  4317. const m = Math.floor(totalSec / 60)
  4318. const s = Math.floor(totalSec % 60)
  4319. return `${fillDigit(m, 2)}:${fillDigit(s, 2)}`
  4320. }
  4321. // 块状时间显示
  4322. const timerBlocks = () => {
  4323. const total = timerIndicator.value.isCountdown
  4324. ? Math.max(timerIndicator.value.remainingSec || 0, 0)
  4325. : Math.max(timerIndicator.value.elapsedSec || 0, 0)
  4326. const h = Math.floor(total / 3600)
  4327. const m = Math.floor((total % 3600) / 60)
  4328. const s = Math.floor(total % 60)
  4329. return {
  4330. h: fillDigit(h, 2),
  4331. m: fillDigit(m, 2),
  4332. s: fillDigit(s, 2),
  4333. }
  4334. }
  4335. // 块可见性:始终显示时分秒
  4336. const timerBlocksVisibility = () => {
  4337. return {
  4338. showH: true,
  4339. showM: true,
  4340. }
  4341. }
  4342. // 根据布局避免遮挡右侧面板
  4343. const getTimerIndicatorRight = () => {
  4344. if (isFullscreen.value) {
  4345. return 16
  4346. }
  4347. if (props.type === '1') {
  4348. // 右侧面板展开时向左让位
  4349. return workPanelCollapsed.value ? 65 : 420
  4350. }
  4351. return 65
  4352. }
  4353. // 计时器本地更新
  4354. const startLocalTick = (isCountdown: boolean) => {
  4355. if (timerInterval.value) {
  4356. clearInterval(timerInterval.value)
  4357. timerInterval.value = null
  4358. }
  4359. timerInterval.value = setInterval(() => {
  4360. if (isCountdown) {
  4361. if (timerIndicator.value.remainingSec !== null) {
  4362. const newRemaining = (timerIndicator.value.remainingSec as number) - 1
  4363. timerIndicator.value.remainingSec = Math.max(newRemaining, 0)
  4364. // 时间到了,标记为完成但保持显示
  4365. if (newRemaining <= 0) {
  4366. timerIndicator.value.finished = true
  4367. timerIndicator.value.remainingSec = 0
  4368. // 保持 visible 为 true,不隐藏
  4369. timerIndicator.value.visible = true
  4370. }
  4371. }
  4372. }
  4373. else {
  4374. if (timerIndicator.value.elapsedSec !== null) {
  4375. timerIndicator.value.elapsedSec = (timerIndicator.value.elapsedSec as number) + 1
  4376. }
  4377. }
  4378. }, 1000) as unknown as number
  4379. }
  4380. // CountdownTimer 事件(仅创建人触发发送)
  4381. const onTimerStart = (payload: { isCountdown: boolean; startAt: string; durationSec?: number }) => {
  4382. timerIndicator.value.visible = true
  4383. timerIndicator.value.isCountdown = payload.isCountdown
  4384. timerIndicator.value.startAt = payload.startAt
  4385. timerIndicator.value.durationSec = payload.isCountdown ? (payload.durationSec || 0) : null
  4386. timerIndicator.value.elapsedSec = payload.isCountdown ? null : 0
  4387. timerIndicator.value.remainingSec = payload.isCountdown ? (payload.durationSec || 0) : null
  4388. timerIndicator.value.finished = false
  4389. startLocalTick(payload.isCountdown)
  4390. if (isCreator.value) {
  4391. sendMessage({ type: 'timer_start', courseid: props.courseid, payload: JSON.stringify(payload) })
  4392. // 持久化状态到 YMap(带运行状态与基线)
  4393. const isCd = payload.isCountdown
  4394. const state: any = {
  4395. visible: true,
  4396. isCountdown: isCd,
  4397. status: 'running',
  4398. startAt: payload.startAt,
  4399. durationSec: isCd ? (payload.durationSec || 0) : null,
  4400. finished: false,
  4401. stopped: false,
  4402. }
  4403. if (isCd) {
  4404. state.remainingBaseSec = payload.durationSec || 0
  4405. state.elapsedBaseSec = null
  4406. }
  4407. else {
  4408. state.elapsedBaseSec = 0
  4409. state.remainingBaseSec = null
  4410. }
  4411. setTimerState(state)
  4412. }
  4413. }
  4414. const onTimerPause = () => {
  4415. if (timerInterval.value) {
  4416. clearInterval(timerInterval.value)
  4417. timerInterval.value = null
  4418. }
  4419. if (isCreator.value) {
  4420. sendMessage({ type: 'timer_pause', courseid: props.courseid })
  4421. // 将当前显示值作为基线写入,并标记暂停
  4422. const isCd = !!timerIndicator.value.isCountdown
  4423. const payload: any = {
  4424. ...getTimerState(),
  4425. status: 'paused',
  4426. pausedAt: new Date().toISOString(),
  4427. finished: !!timerIndicator.value.finished,
  4428. stopped: false,
  4429. }
  4430. if (isCd) {
  4431. payload.remainingBaseSec = Math.max(Number(timerIndicator.value.remainingSec || 0), 0)
  4432. payload.elapsedBaseSec = null
  4433. }
  4434. else {
  4435. payload.elapsedBaseSec = Math.max(Number(timerIndicator.value.elapsedSec || 0), 0)
  4436. payload.remainingBaseSec = null
  4437. }
  4438. setTimerState(payload)
  4439. }
  4440. }
  4441. const onTimerReset = () => {
  4442. if (timerInterval.value) {
  4443. clearInterval(timerInterval.value)
  4444. timerInterval.value = null
  4445. }
  4446. timerIndicator.value = { visible: false, isCountdown: false, startAt: null, durationSec: null, elapsedSec: null, remainingSec: null, finished: false }
  4447. if (isCreator.value) {
  4448. sendMessage({ type: 'timer_reset', courseid: props.courseid })
  4449. clearTimerState()
  4450. }
  4451. }
  4452. const onTimerStop = () => {
  4453. if (timerInterval.value) {
  4454. clearInterval(timerInterval.value)
  4455. timerInterval.value = null
  4456. }
  4457. timerIndicator.value = { visible: false, isCountdown: false, startAt: null, durationSec: null, elapsedSec: null, remainingSec: null, finished: false }
  4458. if (isCreator.value) {
  4459. sendMessage({ type: 'timer_stop', courseid: props.courseid })
  4460. clearTimerState()
  4461. }
  4462. }
  4463. const onTimerFinish = () => {
  4464. timerIndicator.value.finished = true
  4465. // 保持 visible 为 true,时间到了也不消失
  4466. timerIndicator.value.visible = true
  4467. if (timerIndicator.value.isCountdown) {
  4468. timerIndicator.value.remainingSec = 0
  4469. }
  4470. if (timerInterval.value) {
  4471. clearInterval(timerInterval.value)
  4472. timerInterval.value = null
  4473. }
  4474. if (isCreator.value) {
  4475. sendMessage({ type: 'timer_finish', courseid: props.courseid })
  4476. const snap = getTimerState()
  4477. setTimerState({ ...snap, status: 'finished', finished: true, stopped: true, remainingBaseSec: 0 })
  4478. }
  4479. }
  4480. const onTimerUpdate = (payload: { durationSec: number }) => {
  4481. if (isCreator.value && timerIndicator.value.visible && timerIndicator.value.isCountdown) {
  4482. // 重新设置开始时间,重置整个计时
  4483. const newStartAt = new Date().toISOString()
  4484. // 更新本地状态
  4485. timerIndicator.value.startAt = newStartAt
  4486. timerIndicator.value.durationSec = payload.durationSec
  4487. timerIndicator.value.remainingSec = payload.durationSec
  4488. timerIndicator.value.finished = false
  4489. // 重新开始本地计时
  4490. startLocalTick(true)
  4491. // 更新 YMap 状态
  4492. const snap = getTimerState()
  4493. setTimerState({
  4494. ...snap,
  4495. status: 'running',
  4496. startAt: newStartAt,
  4497. durationSec: payload.durationSec,
  4498. remainingBaseSec: payload.durationSec,
  4499. finished: false,
  4500. })
  4501. // 发送消息通知其他用户(使用 timer_start 消息重新开始计时)
  4502. sendMessage({
  4503. type: 'timer_start',
  4504. courseid: props.courseid,
  4505. payload: JSON.stringify({
  4506. isCountdown: true,
  4507. startAt: newStartAt,
  4508. durationSec: payload.durationSec
  4509. })
  4510. })
  4511. }
  4512. }
  4513. // 消息应用(任意端)
  4514. const applyTimerStart = (payload: { isCountdown: boolean; startAt: string; durationSec?: number }) => {
  4515. timerIndicator.value.visible = true
  4516. timerIndicator.value.isCountdown = payload.isCountdown
  4517. timerIndicator.value.startAt = payload.startAt
  4518. timerIndicator.value.durationSec = payload.isCountdown ? (payload.durationSec || 0) : null
  4519. // 以消息时间为基准纠正进度
  4520. const startTs = new Date(payload.startAt).getTime()
  4521. const nowTs = Date.now()
  4522. if (payload.isCountdown) {
  4523. const elapsed = Math.floor((nowTs - startTs) / 1000)
  4524. timerIndicator.value.remainingSec = Math.max((payload.durationSec || 0) - elapsed, 0)
  4525. timerIndicator.value.elapsedSec = null
  4526. }
  4527. else {
  4528. timerIndicator.value.elapsedSec = Math.floor((nowTs - startTs) / 1000)
  4529. timerIndicator.value.remainingSec = null
  4530. }
  4531. timerIndicator.value.finished = false
  4532. startLocalTick(payload.isCountdown)
  4533. }
  4534. const applyTimerPause = () => {
  4535. if (timerInterval.value) {
  4536. clearInterval(timerInterval.value)
  4537. timerInterval.value = null
  4538. }
  4539. }
  4540. const applyTimerReset = () => {
  4541. if (timerInterval.value) {
  4542. clearInterval(timerInterval.value)
  4543. timerInterval.value = null
  4544. }
  4545. timerIndicator.value = { visible: false, isCountdown: false, startAt: null, durationSec: null, elapsedSec: null, remainingSec: null, finished: false }
  4546. }
  4547. const applyTimerStop = () => {
  4548. if (timerInterval.value) {
  4549. clearInterval(timerInterval.value)
  4550. timerInterval.value = null
  4551. }
  4552. timerIndicator.value = { visible: false, isCountdown: false, startAt: null, durationSec: null, elapsedSec: null, remainingSec: null, finished: false }
  4553. }
  4554. const applyTimerFinish = () => {
  4555. timerIndicator.value.finished = true
  4556. // 保持 visible 为 true,时间到了也不消失
  4557. timerIndicator.value.visible = true
  4558. if (timerIndicator.value.isCountdown) {
  4559. timerIndicator.value.remainingSec = 0
  4560. }
  4561. if (timerInterval.value) {
  4562. clearInterval(timerInterval.value)
  4563. timerInterval.value = null
  4564. }
  4565. }
  4566. const applyTimerUpdate = (payload: { durationSec: number; startAt?: string }) => {
  4567. if (timerIndicator.value.visible && timerIndicator.value.isCountdown) {
  4568. const newStartAt = payload.startAt || new Date().toISOString()
  4569. // 更新状态
  4570. timerIndicator.value.startAt = newStartAt
  4571. timerIndicator.value.durationSec = payload.durationSec
  4572. timerIndicator.value.remainingSec = payload.durationSec
  4573. timerIndicator.value.finished = false
  4574. // 重新开始本地计时
  4575. startLocalTick(true)
  4576. }
  4577. }
  4578. // 应用激光笔共享状态(任意端)
  4579. const applyLaserStateSnapshot = (snap: any) => {
  4580. if (!snap) return
  4581. const enabled = snap.enabled !== undefined ? !!snap.enabled : laserPenOverlay.value.visible
  4582. const x = typeof snap.x === 'number' ? snap.x : null
  4583. const y = typeof snap.y === 'number' ? snap.y : null
  4584. if (props.type == '2') {
  4585. // 更新开关状态
  4586. if (snap.enabled !== undefined) {
  4587. laserPenOverlay.value.visible = enabled
  4588. }
  4589. // 如果激光笔是开启状态,更新位置
  4590. if (laserPenOverlay.value.visible && x != null && y != null) {
  4591. laserPenOverlay.value.xPct = x
  4592. laserPenOverlay.value.yPct = y
  4593. refreshLaserOverlayRect()
  4594. if (laserMoveRafId) cancelAnimationFrame(laserMoveRafId)
  4595. laserMoveRafId = requestAnimationFrame(updateLaserDotPosition)
  4596. }
  4597. }
  4598. }
  4599. // YMap 状态应用
  4600. const applyTimerStateSnapshot = (snap: any) => {
  4601. if (!snap || !snap.visible) {
  4602. return
  4603. }
  4604. const isCountdown = !!snap.isCountdown
  4605. const status = snap.status as string | undefined
  4606. const startAt = snap.startAt as string
  4607. const durationSec = isCountdown ? Number(snap.durationSec || 0) : null
  4608. const finished = !!snap.finished
  4609. const elapsedBaseSec = snap.elapsedBaseSec != null ? Number(snap.elapsedBaseSec) : null
  4610. const remainingBaseSec = snap.remainingBaseSec != null ? Number(snap.remainingBaseSec) : null
  4611. timerIndicator.value.visible = true
  4612. timerIndicator.value.isCountdown = isCountdown
  4613. timerIndicator.value.startAt = startAt
  4614. timerIndicator.value.durationSec = durationSec
  4615. const startTs = new Date(startAt).getTime()
  4616. const nowTs = Date.now()
  4617. if (isCountdown) {
  4618. if (status === 'paused') {
  4619. timerIndicator.value.remainingSec = Math.max(remainingBaseSec || 0, 0)
  4620. timerIndicator.value.elapsedSec = null
  4621. timerIndicator.value.finished = !!finished || (timerIndicator.value.remainingSec as number) <= 0
  4622. if (timerInterval.value) {
  4623. clearInterval(timerInterval.value); timerInterval.value = null
  4624. }
  4625. return
  4626. }
  4627. const base = remainingBaseSec != null ? remainingBaseSec : (durationSec || 0)
  4628. const elapsed = Math.floor((nowTs - startTs) / 1000)
  4629. timerIndicator.value.remainingSec = Math.max(base - elapsed, 0)
  4630. timerIndicator.value.elapsedSec = null
  4631. if (finished || (timerIndicator.value.remainingSec as number) <= 0) {
  4632. timerIndicator.value.finished = true
  4633. timerIndicator.value.remainingSec = 0
  4634. // 保持 visible 为 true,时间到了也不消失
  4635. timerIndicator.value.visible = true
  4636. if (timerInterval.value) {
  4637. clearInterval(timerInterval.value); timerInterval.value = null
  4638. }
  4639. }
  4640. else {
  4641. timerIndicator.value.finished = false
  4642. startLocalTick(true)
  4643. }
  4644. }
  4645. else {
  4646. if (status === 'paused') {
  4647. timerIndicator.value.elapsedSec = Math.max(elapsedBaseSec || 0, 0)
  4648. timerIndicator.value.remainingSec = null
  4649. timerIndicator.value.finished = !!finished
  4650. if (timerInterval.value) {
  4651. clearInterval(timerInterval.value); timerInterval.value = null
  4652. }
  4653. return
  4654. }
  4655. const base = elapsedBaseSec != null ? elapsedBaseSec : 0
  4656. const elapsed = Math.floor((nowTs - startTs) / 1000)
  4657. timerIndicator.value.elapsedSec = base + elapsed
  4658. timerIndicator.value.remainingSec = null
  4659. if (finished) {
  4660. if (timerInterval.value) {
  4661. clearInterval(timerInterval.value); timerInterval.value = null
  4662. }
  4663. timerIndicator.value.finished = true
  4664. }
  4665. else {
  4666. timerIndicator.value.finished = false
  4667. startLocalTick(false)
  4668. }
  4669. }
  4670. }
  4671. // 读写 YMap 工具
  4672. const getTimerState = () => {
  4673. if (!yTimerState.value) return {}
  4674. return yTimerState.value.toJSON()
  4675. }
  4676. const setTimerState = (state: any) => {
  4677. if (!yTimerState.value) return
  4678. docSocket.value?.transact(() => {
  4679. Object.entries(state).forEach(([k, v]) => yTimerState.value.set(k, v as any))
  4680. yTimerState.value.set('visible', true)
  4681. })
  4682. }
  4683. const clearTimerState = () => {
  4684. if (!yTimerState.value) return
  4685. docSocket.value?.transact(() => {
  4686. yTimerState.value.clear()
  4687. })
  4688. }
  4689. </script>
  4690. <style lang="scss" scoped>
  4691. .pptist-student-viewer {
  4692. height: 100vh;
  4693. display: flex;
  4694. background-color: #f4f4f4;
  4695. padding: 15px 0;
  4696. box-sizing: border-box;
  4697. // 全屏模式样式
  4698. &.fullscreen {
  4699. padding: 0;
  4700. .layout-content-left {
  4701. display: none; // 全屏时隐藏左侧导航栏
  4702. }
  4703. .layout-content-right {
  4704. display: none; // 全屏时隐藏左侧导航栏
  4705. }
  4706. .viewer-header {
  4707. display: none; // 全屏时隐藏顶部标题栏
  4708. }
  4709. }
  4710. // 激光笔模式样式
  4711. }
  4712. .layout-content-left {
  4713. width: 200px;
  4714. height: 100%;
  4715. background-color: #fff;
  4716. border-radius: 0 5px 0 5px;
  4717. overflow: hidden;
  4718. transition: width .2s ease;
  4719. margin: 10px;
  4720. }
  4721. .layout-content-left.collapsed {
  4722. width: 48px;
  4723. margin-left: 0;
  4724. }
  4725. .slide-header {
  4726. display: flex;
  4727. align-items: center;
  4728. justify-content: space-between;
  4729. }
  4730. /* 收缩时头部仅显示按钮,并保持按钮在可用宽度内水平居中 */
  4731. .layout-content-left.collapsed .slide-header {
  4732. justify-content: center;
  4733. padding: 8px;
  4734. }
  4735. .layout-content-right {
  4736. width: 350px;
  4737. height: 100%;
  4738. background-color: #fff;
  4739. border-radius: 5px 0 5px 0;
  4740. overflow: hidden;
  4741. transition: width .2s ease;
  4742. position: relative;
  4743. margin: 10px;
  4744. }
  4745. .panel-content {
  4746. margin-right: 0;
  4747. // padding: 0 8px;
  4748. height: calc(100% - 65px);
  4749. overflow: auto;
  4750. }
  4751. .layout-content-right.collapsed {
  4752. width: 52px;
  4753. margin-right: 0px;
  4754. }
  4755. .right-panel-header {
  4756. display: flex;
  4757. align-items: center;
  4758. justify-content: space-between;
  4759. }
  4760. /* 侧边导航标签样式 */
  4761. .side-nav-tabs {
  4762. position: absolute;
  4763. right: 0;
  4764. top: 60px;
  4765. bottom: 0;
  4766. width: 52px;
  4767. display: flex;
  4768. flex-direction: column;
  4769. gap: 8px;
  4770. padding: 8px 0;
  4771. align-items: center;
  4772. background: #fff;
  4773. border-left: 1px solid #e0e0e0;
  4774. z-index: 10;
  4775. }
  4776. .side-nav-btn {
  4777. width: 45px;
  4778. height: 45px;
  4779. min-height: 45px;
  4780. border: 1px solid #d9d9d9;
  4781. background: #fff;
  4782. border-radius: 6px;
  4783. cursor: pointer;
  4784. transition: all 0.2s;
  4785. display: flex;
  4786. align-items: center;
  4787. justify-content: center;
  4788. padding: 8px;
  4789. gap: 8px;
  4790. overflow: hidden;
  4791. &:hover {
  4792. border-color: #1890ff;
  4793. transform: scale(1.02);
  4794. }
  4795. &.active {
  4796. border-color: #3681fc;
  4797. background: #3681fc;
  4798. box-shadow: 0 0 0 2px rgba(54, 129, 252, 0.2);
  4799. }
  4800. img {
  4801. width: 25px;
  4802. height: 25px;
  4803. object-fit: contain;
  4804. flex-shrink: 0;
  4805. }
  4806. span {
  4807. font-size: 12px;
  4808. font-weight: 500;
  4809. color: #333;
  4810. white-space: nowrap;
  4811. overflow: hidden;
  4812. text-overflow: ellipsis;
  4813. }
  4814. &.active span {
  4815. color: #fff;
  4816. }
  4817. }
  4818. /* 收缩时头部仅显示按钮,并保持按钮在可用宽度内水平居中 */
  4819. .layout-content-right.collapsed .right-panel-header {
  4820. justify-content: center;
  4821. padding: 8px;
  4822. }
  4823. /* 收缩状态下的切换按钮 */
  4824. .collapsed-tabs {
  4825. display: flex;
  4826. flex-direction: column;
  4827. gap: 8px;
  4828. // padding: 8px;
  4829. align-items: center;
  4830. }
  4831. .collapsed-tab-btn {
  4832. width: 32px;
  4833. height: 32px;
  4834. border: 1px solid #d9d9d9;
  4835. background: #fff;
  4836. border-radius: 6px;
  4837. cursor: pointer;
  4838. transition: all 0.2s;
  4839. display: flex;
  4840. align-items: center;
  4841. justify-content: center;
  4842. padding: 0;
  4843. overflow: hidden;
  4844. &:hover {
  4845. border-color: #1890ff;
  4846. transform: scale(1.05);
  4847. }
  4848. &.active {
  4849. border-color: #3681fc;
  4850. background: #3681fc;
  4851. box-shadow: 0 0 0 2px rgba(54, 129, 252, 0.2);
  4852. }
  4853. img {
  4854. width: 20px;
  4855. height: 20px;
  4856. object-fit: contain;
  4857. transition: transform 0.2s;
  4858. }
  4859. &:hover img {
  4860. transform: scale(1.1);
  4861. }
  4862. }
  4863. .collapse-btn {
  4864. display: inline-flex;
  4865. align-items: center;
  4866. justify-content: center;
  4867. width: 32px;
  4868. height: 32px;
  4869. // border: 1px solid #d9d9d9;
  4870. border: none;
  4871. border-radius: 8px;
  4872. background: #fff;
  4873. color: #333;
  4874. cursor: pointer;
  4875. line-height: 1;
  4876. font-weight: 700;
  4877. position: absolute;
  4878. }
  4879. .collapse-btn:hover {
  4880. // border-color: #1890ff;
  4881. // color: #1890ff;
  4882. }
  4883. .homework-title {
  4884. padding: 12px 12px 0 12px;
  4885. color: #333;
  4886. font-size: 14px;
  4887. font-weight: 600;
  4888. }
  4889. .homework-grid {
  4890. display: grid;
  4891. grid-template-columns: repeat(4, 1fr);
  4892. gap: 16px;
  4893. padding: 12px;
  4894. }
  4895. .homework-btn {
  4896. display: inline-flex;
  4897. align-items: center;
  4898. justify-content: center;
  4899. width: 100%;
  4900. min-width: 0;
  4901. height: 35px;
  4902. border: 1px solid #2f80ed;
  4903. color: #2f80ed;
  4904. background: #fff;
  4905. border-radius: 8px;
  4906. cursor: pointer;
  4907. font-weight: 600;
  4908. overflow: hidden;
  4909. padding: 0 10px;
  4910. text-align: center;
  4911. }
  4912. .homework-btn__text {
  4913. display: block;
  4914. max-width: 100%;
  4915. overflow: hidden;
  4916. white-space: nowrap;
  4917. text-overflow: ellipsis;
  4918. }
  4919. .homework-btn:hover {
  4920. box-shadow: 0 2px 10px rgba(0,0,0,0.08);
  4921. }
  4922. .homework-btn.unsubmitted {
  4923. border-color: #d9d9d9;
  4924. color: #999;
  4925. background: #f5f5f5;
  4926. cursor: not-allowed;
  4927. }
  4928. .homework-btn.unsubmitted:hover {
  4929. box-shadow: none;
  4930. transform: none;
  4931. }
  4932. .homework-loading {
  4933. padding: 12px;
  4934. color: #666;
  4935. font-size: 13px;
  4936. }
  4937. .homework-empty {
  4938. padding: 12px;
  4939. color: #999;
  4940. font-size: 13px;
  4941. }
  4942. .thumbnails {
  4943. padding: 0;
  4944. height: 100%;
  4945. .viewer-header {
  4946. margin-bottom: 16px;
  4947. h3 {
  4948. margin: 0;
  4949. font-size: 16px;
  4950. font-weight: 600;
  4951. color: #333;
  4952. text-align: center;
  4953. width: 100%;
  4954. }
  4955. }
  4956. .thumbnail-list {
  4957. width: 100%;
  4958. padding: 0 16px;
  4959. box-sizing: border-box;
  4960. .thumbnail-item {
  4961. position: relative;
  4962. margin-bottom: 12px;
  4963. cursor: pointer;
  4964. border-radius: 8px;
  4965. overflow: hidden;
  4966. transition: all 0.2s ease;
  4967. border: 2px solid rgba(24, 144, 255, 0.2);
  4968. &:hover {
  4969. transform: translateY(-2px);
  4970. box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  4971. border-color: rgba(24, 144, 255, 0.4);
  4972. }
  4973. &.active {
  4974. border: 2px solid #1890ff;
  4975. box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  4976. }
  4977. .label {
  4978. position: absolute;
  4979. top: 8px;
  4980. left: 8px;
  4981. background-color: rgba(0, 0, 0, 0.6);
  4982. color: #fff;
  4983. padding: 2px 6px;
  4984. border-radius: 4px;
  4985. font-size: 12px;
  4986. font-weight: 600;
  4987. z-index: 1;
  4988. }
  4989. .thumbnail {
  4990. width: 100%;
  4991. height: auto;
  4992. }
  4993. }
  4994. }
  4995. .page-number {
  4996. text-align: center;
  4997. margin-top: 16px;
  4998. padding: 8px;
  4999. background-color: #f0f0f0;
  5000. border-radius: 4px;
  5001. font-size: 14px;
  5002. color: #666;
  5003. }
  5004. .progress-bar {
  5005. margin-top: 12px;
  5006. height: 6px;
  5007. background-color: #f0f0f0;
  5008. border-radius: 3px;
  5009. overflow: hidden;
  5010. .progress-fill {
  5011. height: 100%;
  5012. background: linear-gradient(90deg, #1890ff, #40a9ff);
  5013. border-radius: 3px;
  5014. transition: width 0.3s ease;
  5015. }
  5016. }
  5017. }
  5018. .layout-content-center {
  5019. flex: 1;
  5020. display: flex;
  5021. flex-direction: column;
  5022. background-color: #000;
  5023. }
  5024. .viewer-header {
  5025. height: 45px;
  5026. background-color: #fff;
  5027. border-bottom: 1px solid #e0e0e0;
  5028. display: flex;
  5029. align-items: center;
  5030. justify-content: space-between;
  5031. padding: 0 8px;
  5032. transition: transform 0.3s ease;
  5033. position: relative;
  5034. &.hidden {
  5035. transform: translateY(-100%);
  5036. }
  5037. .slide-title {
  5038. font-size: 18px;
  5039. font-weight: 600;
  5040. color: #333;
  5041. }
  5042. .viewer-controls {
  5043. display: flex;
  5044. gap: 12px;
  5045. button {
  5046. padding: 8px 12px;
  5047. border: 1px solid #d9d9d9;
  5048. border-radius: 6px;
  5049. background-color: #fff;
  5050. color: #333;
  5051. cursor: pointer;
  5052. transition: all 0.2s ease;
  5053. display: flex;
  5054. align-items: center;
  5055. justify-content: center;
  5056. min-width: 40px;
  5057. height: 36px;
  5058. &:hover:not(:disabled) {
  5059. border-color: #1890ff;
  5060. color: #1890ff;
  5061. }
  5062. &:disabled {
  5063. opacity: 0.5;
  5064. cursor: not-allowed;
  5065. }
  5066. &.back-btn {
  5067. background-color: #1890ff;
  5068. color: #fff;
  5069. border-color: #1890ff;
  5070. &:hover {
  5071. background-color: #40a9ff;
  5072. border-color: #40a9ff;
  5073. }
  5074. }
  5075. &.follow-active {
  5076. background-color: #3681fc;
  5077. color: #fff !important;
  5078. border-color: #3681fc;
  5079. &:hover {
  5080. background-color: #2d6fd9;
  5081. border-color: #2d6fd9;
  5082. color: #fff !important;
  5083. }
  5084. }
  5085. .control-icon {
  5086. font-size: 16px;
  5087. }
  5088. }
  5089. }
  5090. }
  5091. .viewer-canvas {
  5092. flex: 1;
  5093. position: relative;
  5094. background-color: rgb(244, 244, 244);
  5095. overflow: hidden;
  5096. // 全屏时隐藏滚动条和边框
  5097. &.fullscreen-mode {
  5098. overflow: hidden !important;
  5099. background-color: transparent !important;
  5100. }
  5101. }
  5102. .slide-list-wrap {
  5103. position: absolute;
  5104. overflow: hidden;
  5105. background-color: #fff;
  5106. box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.01), 0 0 12px 0 rgba(0, 0, 0, 0.1);
  5107. border-radius: 8px;
  5108. /* 全屏时去掉圆角 */
  5109. .pptist-student-viewer.fullscreen & {
  5110. border-radius: 0;
  5111. }
  5112. }
  5113. .slide-list-wrap-n{
  5114. border: 5px solid #595959;
  5115. background: #000;
  5116. padding: 65px 0 0 0;
  5117. box-sizing: border-box;
  5118. }
  5119. /* 学生端激光笔覆盖层与小圆点样式(拦截点击) */
  5120. .laser-pointer-overlay {
  5121. position: fixed;
  5122. inset: 0;
  5123. z-index: 1000;
  5124. pointer-events: auto;
  5125. }
  5126. .laser-pointer-dot {
  5127. position: absolute;
  5128. width: 24px;
  5129. height: 24px;
  5130. pointer-events: none;
  5131. /* 复用 .laser-pen 的光点视觉(使用与 cursor 相同的图) */
  5132. background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAABHNCSVQICAgIfAhkiAAACCJJREFUWIXtmLuO3MYShv/qZl9IzqwXo2BkSAtsIK+z8wwOBcOJ9C56Cr2LlThQcgBnfofVBnswXlgTaLHaIdk3dtcJOKOzd8n2MeDABRDDgKz/m+pudv0N/BN/Luj/kYSZJQBxJR8DKESU/2zuPwTIzAKnpxqHhxUuLir0vYSUAkS0ewA5F7Rtxv7+iNPTEYeHkYjKXwrIzHK9XtultRohaKSkkFIVhqGCEAIxTvm0ZpRSTNOMUGqEUgnGxLX3cblc+t9T2S8GXK1W9dP53OLiwoLZhMtLQ4CiGBVKkchZIOcpn5QMKQuEyKx1YiCZvb0AooD9ff/rZuMPDg7cl+hWn3uAmQWABut1g/PzOnZdTd5bMY6aQtAIQQGQGEd5bYirKgPIZExiY2IKIbK1XpeinzaN2s7b4XPD/iAgM0ucn7fYbNrQ963Juaauq8k5i3E01PcG46iQs0TO1wGlzJAyo6oS2jagqgLGUQNQwTllvJeYzwUz9w8N+b2AzCxwft6i72fBuZkYhnbcbBqKsSbvazhnEIJBzqrEqGQpAlO1AaKShShC6wQpE4UQUNcBKenReyXm8yoIIYwQtNXq7qvkQxVssNm0wbmZuLiYUQgtnGtps2ngfQ3vLaVkEKOmGKcqMtMWkEnKTFonaB3Z+4AQPFmreD6vSAghxpECAFMKY7EoALovBlytVjXW6yb0fSuGoaUQWrq8nKHvW/R9S943xbmavJ+qmNIO8FMFIWXert7A1gYxjprHsSLmaTHt7UF0HYdSilmv82q1ynctnFuAzCzx8aPF+Xltcq7HzaaBcy36vsUwzKjrZhiGRgxDA+8tUjIUgkbOEqVMgEIUkjLDmAjvgwjBI6WKxlHybp5KyVRKMcaMGIb0dLFIzBxvzsdbgOv12i69t7HrpgURY02bTYO+b6nrZui6qZLONdz3jTg5ORDHx0f48OExQpgBAIzp8OjRez46Oi7Pnq1ot5BKETQVgYmosJRj6rrEQNJCxLX3EUB/LyAzC3z8qOGcIe8tOWdpmm81ed9gGJpdJdF1rXz79jucnX1za454P8fZ2ZzOzr6Rx8fvyvPnP38afiEKVVXmqhrJ+wSlIqoqYj73S2s1M7urC0ZcS3x6qhGCDpeXBuOoMY4Gzhl4b4tzNYahgXMNuq4Vb978cCfczTg7+0a8efMDuq6Fcw2GoSnO1fDewjmDcTQYx0kzBI3TU3319euAh4cVUlIEKApBU98bhGAoJSO8N/Dect834u3b73B+/vVn4XZxfv61ePv2O+77Bt5b4b2hlKbcfW8oBE2AQkoKh4fXRvU64MVFhZQqilEhBLX9CCvEqLer1YiTk4MvqtxdlTw5OcAWDDFq5DxphDBtmSlNzcddgMws0fcyDEOFUiQAiZxliVGVGFVJSXEImo6Pj3433Dbo+PiIQ9AlJbXLi5wnrVIm7b6X223wOiAAASkFhBDIWWAcJXKWshQhcpYiZ0k5S3z48PhO9ZcvgV9+ma6XL+8m/PDhMW1ziW1u5Cy3WpO2lOIq11VAAhEhRkLO0z0RgVmAefotRXz6lNyMV6+AxWK6Xr26GzCEGXZb4i7nTifnSXv6Tn7qssTdmf4+cRWQwczQmiHldM/MICogmn6FKDDmzj0Tr18D5+fT9fr13WrGdBCiXMu505Fy0mZmTJYBwPUPdUHOBaUUSFlQVRlS5rzbtqTMJGXGo0fvcXY2vyX+44/T9VA8evSepcy8zcdCFDG1ZBlSTto5FwC3P9RElNG22TTNCCEygAwps9A6Ca2TUCqRMZGPjo4fprg/+OjomIyJQqm0ywspJy0hJu22zVf34+tzcH9/hFIja51gTEJVJUiZoHWEMQFKhfLs2QpPnrz73XRPnrwrz56toFSAMQFaR0g5aRiTWOsEpUbs749XX7u51Y1QKjGQ2JjIbRtgTGClQrE2wFpPbTuU589/xmLx2xfDLRa/lefPf6a2HWCtL9YG3oJy2wY2JjKQoFTC6ekDgIeHEcZEs7cXUFURVTV1wtZ6UdcOTTOgrgfMZn158eKnL6rkkyfvyosXP2E261HXA5pmEHXtYK1HXU9WoKomTWMiDg/j1devbStEVN6/fx+XRIGt9RhHjZQ0Wat4HCsax//1fEQlf//9v8XJyTF9rt1q2+mPtW2PphnY2gHWOrbWcV17ttaDKKy9j4/398u9gACwXC49Pn7UuhQNQI3eT206s2DadptCFEiZqaoS/+tfvnz77X/oRsPKUmYyJpJSAdZ6NM2Aphl4Pu/QND3P5wO0dmo2c5jNHPb3/fKrr/xNnluARJRXq5V/2jQqOKfE1kPsPC8zM1VVLkqNwpiAEAxbq+hGy89SZtq2/MXaIOrasbUDmqZH2/Zo257bdghSOtM07tfNxh/s799yd3d6koODA8fM0ngvw9bgYG9vatOJClfVSFUVYe3UldxhmiBlxtY0kVLTlLHW8Xw+oG17NqYvs1lv6rrHcjkcEN1p5B9ydQPmc2GEoABAdB1TKYWlnDph5wJvbSdPpwvXbCcLUXhrO2FMQF0HttZBa8dtO5TZrDdt26FtewDDfRD3AhJRYeYemKxh2Bqc1HVTm17Xn4y7yFnyDeMurhh33hp3rmuvZjMXpHSmrqehXiz6h04XHjxZIKLMzB0Wi2LW64xhSAwkVFXEOGpo/dmjD2yPPlBVka31mM2caRqH5XLAnz362FUSQLdarfLTxSJpISLmcx8uLw217R8/PLpnzt3S/5KHdvG3Pn67Afr3PMB8APgvOwL+J/5s/BeEBm1u1Gu4+QAAAABJRU5ErkJggg==);
  5133. background-repeat: no-repeat;
  5134. background-position: center center;
  5135. background-size: contain;
  5136. /* 居中到指针 */
  5137. transform: translate3d(-12px, -12px, 0);
  5138. will-change: transform;
  5139. }
  5140. .laser-pen {
  5141. cursor: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAABHNCSVQICAgIfAhkiAAACCJJREFUWIXtmLuO3MYShv/qZl9IzqwXo2BkSAtsIK+z8wwOBcOJ9C56Cr2LlThQcgBnfofVBnswXlgTaLHaIdk3dtcJOKOzd8n2MeDABRDDgKz/m+pudv0N/BN/Luj/kYSZJQBxJR8DKESU/2zuPwTIzAKnpxqHhxUuLir0vYSUAkS0ewA5F7Rtxv7+iNPTEYeHkYjKXwrIzHK9XtultRohaKSkkFIVhqGCEAIxTvm0ZpRSTNOMUGqEUgnGxLX3cblc+t9T2S8GXK1W9dP53OLiwoLZhMtLQ4CiGBVKkchZIOcpn5QMKQuEyKx1YiCZvb0AooD9ff/rZuMPDg7cl+hWn3uAmQWABut1g/PzOnZdTd5bMY6aQtAIQQGQGEd5bYirKgPIZExiY2IKIbK1XpeinzaN2s7b4XPD/iAgM0ucn7fYbNrQ963Juaauq8k5i3E01PcG46iQs0TO1wGlzJAyo6oS2jagqgLGUQNQwTllvJeYzwUz9w8N+b2AzCxwft6i72fBuZkYhnbcbBqKsSbvazhnEIJBzqrEqGQpAlO1AaKShShC6wQpE4UQUNcBKenReyXm8yoIIYwQtNXq7qvkQxVssNm0wbmZuLiYUQgtnGtps2ngfQ3vLaVkEKOmGKcqMtMWkEnKTFonaB3Z+4AQPFmreD6vSAghxpECAFMKY7EoALovBlytVjXW6yb0fSuGoaUQWrq8nKHvW/R9S943xbmavJ+qmNIO8FMFIWXert7A1gYxjprHsSLmaTHt7UF0HYdSilmv82q1ynctnFuAzCzx8aPF+Xltcq7HzaaBcy36vsUwzKjrZhiGRgxDA+8tUjIUgkbOEqVMgEIUkjLDmAjvgwjBI6WKxlHybp5KyVRKMcaMGIb0dLFIzBxvzsdbgOv12i69t7HrpgURY02bTYO+b6nrZui6qZLONdz3jTg5ORDHx0f48OExQpgBAIzp8OjRez46Oi7Pnq1ot5BKETQVgYmosJRj6rrEQNJCxLX3EUB/LyAzC3z8qOGcIe8tOWdpmm81ed9gGJpdJdF1rXz79jucnX1za454P8fZ2ZzOzr6Rx8fvyvPnP38afiEKVVXmqhrJ+wSlIqoqYj73S2s1M7urC0ZcS3x6qhGCDpeXBuOoMY4Gzhl4b4tzNYahgXMNuq4Vb978cCfczTg7+0a8efMDuq6Fcw2GoSnO1fDewjmDcTQYx0kzBI3TU3319euAh4cVUlIEKApBU98bhGAoJSO8N/Dect834u3b73B+/vVn4XZxfv61ePv2O+77Bt5b4b2hlKbcfW8oBE2AQkoKh4fXRvU64MVFhZQqilEhBLX9CCvEqLer1YiTk4MvqtxdlTw5OcAWDDFq5DxphDBtmSlNzcddgMws0fcyDEOFUiQAiZxliVGVGFVJSXEImo6Pj3433Dbo+PiIQ9AlJbXLi5wnrVIm7b6X223wOiAAASkFhBDIWWAcJXKWshQhcpYiZ0k5S3z48PhO9ZcvgV9+ma6XL+8m/PDhMW1ziW1u5Cy3WpO2lOIq11VAAhEhRkLO0z0RgVmAefotRXz6lNyMV6+AxWK6Xr26GzCEGXZb4i7nTifnSXv6Tn7qssTdmf4+cRWQwczQmiHldM/MICogmn6FKDDmzj0Tr18D5+fT9fr13WrGdBCiXMu505Fy0mZmTJYBwPUPdUHOBaUUSFlQVRlS5rzbtqTMJGXGo0fvcXY2vyX+44/T9VA8evSepcy8zcdCFDG1ZBlSTto5FwC3P9RElNG22TTNCCEygAwps9A6Ca2TUCqRMZGPjo4fprg/+OjomIyJQqm0ywspJy0hJu22zVf34+tzcH9/hFIja51gTEJVJUiZoHWEMQFKhfLs2QpPnrz73XRPnrwrz56toFSAMQFaR0g5aRiTWOsEpUbs749XX7u51Y1QKjGQ2JjIbRtgTGClQrE2wFpPbTuU589/xmLx2xfDLRa/lefPf6a2HWCtL9YG3oJy2wY2JjKQoFTC6ekDgIeHEcZEs7cXUFURVTV1wtZ6UdcOTTOgrgfMZn158eKnL6rkkyfvyosXP2E261HXA5pmEHXtYK1HXU9WoKomTWMiDg/j1devbStEVN6/fx+XRIGt9RhHjZQ0Wat4HCsax//1fEQlf//9v8XJyTF9rt1q2+mPtW2PphnY2gHWOrbWcV17ttaDKKy9j4/398u9gACwXC49Pn7UuhQNQI3eT206s2DadptCFEiZqaoS/+tfvnz77X/oRsPKUmYyJpJSAdZ6NM2Aphl4Pu/QND3P5wO0dmo2c5jNHPb3/fKrr/xNnluARJRXq5V/2jQqOKfE1kPsPC8zM1VVLkqNwpiAEAxbq+hGy89SZtq2/MXaIOrasbUDmqZH2/Zo257bdghSOtM07tfNxh/s799yd3d6koODA8fM0ngvw9bgYG9vatOJClfVSFUVYe3UldxhmiBlxtY0kVLTlLHW8Xw+oG17NqYvs1lv6rrHcjkcEN1p5B9ydQPmc2GEoABAdB1TKYWlnDph5wJvbSdPpwvXbCcLUXhrO2FMQF0HttZBa8dtO5TZrDdt26FtewDDfRD3AhJRYeYemKxh2Bqc1HVTm17Xn4y7yFnyDeMurhh33hp3rmuvZjMXpHSmrqehXiz6h04XHjxZIKLMzB0Wi2LW64xhSAwkVFXEOGpo/dmjD2yPPlBVka31mM2caRqH5XLAnz362FUSQLdarfLTxSJpISLmcx8uLw217R8/PLpnzt3S/5KHdvG3Pn67Afr3PMB8APgvOwL+J/5s/BeEBm1u1Gu4+QAAAABJRU5ErkJggg==) 20 20, default !important;
  5142. }
  5143. .slide-bottom{
  5144. height: 60px;
  5145. background: #000;
  5146. position: relative;
  5147. z-index: 10;
  5148. posttion: relative;
  5149. }
  5150. .slide-bottom-center{
  5151. position: absolute;
  5152. left: 50%;
  5153. top: 50%;
  5154. transform: translate(-50%, -50%);
  5155. }
  5156. .slide-bottom-center-item{
  5157. display: flex;
  5158. align-items: center;
  5159. justify-content: center;
  5160. gap: 15px;
  5161. img{
  5162. width: 24px;
  5163. height: 24px;
  5164. cursor: pointer;
  5165. }
  5166. .slide-bottom-center-item-page{
  5167. color: #fff;
  5168. font-size: 16px;
  5169. font-weight: 600;
  5170. display: flex;
  5171. gap: 5px;
  5172. }
  5173. }
  5174. .slide-bottom-right{
  5175. position: absolute;
  5176. right: 20px;
  5177. top: 50%;
  5178. transform: translateY(-50%);
  5179. display: flex;
  5180. align-items: center;
  5181. justify-content: center;
  5182. gap: 15px;
  5183. font-size: 24px;
  5184. color: #fff;
  5185. .tool-btn {
  5186. cursor: pointer;
  5187. &:hover,
  5188. &.active {
  5189. color: #1890ff;
  5190. }
  5191. &+.tool-btn {
  5192. margin-left: 15px;
  5193. }
  5194. }
  5195. .upBtn{
  5196. // border-bottom: 3px solid #fff;
  5197. // padding-bottom: 3px;
  5198. width: 24px;
  5199. height: 24px;
  5200. &:hover,
  5201. &.active {
  5202. border-color: #1890ff;
  5203. }
  5204. }
  5205. .tool-btn.loading {
  5206. animation: icon-rotate 1s linear infinite;
  5207. }
  5208. @keyframes icon-rotate {
  5209. 100% { transform: rotate(360deg); }
  5210. }
  5211. }
  5212. .upBtn :deep(svg) {
  5213. width: calc(1em - 3px) !important;
  5214. height: calc(1em - 3px) !important;
  5215. }
  5216. .loading-indicator {
  5217. position: absolute;
  5218. top: 50%;
  5219. left: 50%;
  5220. transform: translate(-50%, -50%);
  5221. display: flex;
  5222. align-items: center;
  5223. justify-content: center;
  5224. z-index: 10;
  5225. .loading-text {
  5226. color: #666;
  5227. font-size: 14px;
  5228. background-color: rgba(255, 255, 255, 0.9);
  5229. padding: 12px 20px;
  5230. border-radius: 6px;
  5231. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  5232. }
  5233. }
  5234. // 全屏模式样式
  5235. .fullscreen-slide {
  5236. // 使用放映功能的默认样式
  5237. }
  5238. // 全屏工具按钮样式,直接复制放映功能的样式
  5239. .tools-left {
  5240. position: fixed;
  5241. bottom: 8px;
  5242. left: 8px;
  5243. font-size: 25px;
  5244. color: #666;
  5245. z-index: 10;
  5246. .tool-btn {
  5247. opacity: .3;
  5248. cursor: pointer;
  5249. transition: opacity 0.3s;
  5250. &:hover {
  5251. opacity: .95;
  5252. }
  5253. &+.tool-btn {
  5254. margin-left: 8px;
  5255. }
  5256. }
  5257. }
  5258. .tools-right {
  5259. height: 66px;
  5260. position: fixed;
  5261. bottom: -66px;
  5262. right: 0;
  5263. z-index: 5;
  5264. padding: 8px;
  5265. transition: bottom 0.3s;
  5266. &.visible {
  5267. bottom: 0;
  5268. }
  5269. &::after {
  5270. content: '';
  5271. width: 100%;
  5272. height: 66px;
  5273. position: absolute;
  5274. left: 0;
  5275. top: -66px;
  5276. }
  5277. .content {
  5278. width: 100%;
  5279. height: 100%;
  5280. display: flex;
  5281. justify-content: center;
  5282. align-items: center;
  5283. border-radius: 4px;
  5284. font-size: 25px;
  5285. background-color: #fff;
  5286. color: #333;
  5287. padding: 8px 10px;
  5288. box-shadow: 0 2px 12px 0 rgb(56, 56, 56, .2);
  5289. border: 1px solid #e2e6ed;
  5290. }
  5291. .tool-btn {
  5292. cursor: pointer;
  5293. &:hover,
  5294. &.active {
  5295. color: #1890ff;
  5296. }
  5297. &+.tool-btn {
  5298. margin-left: 15px;
  5299. }
  5300. }
  5301. .page-number {
  5302. font-size: 12px;
  5303. padding: 0 12px;
  5304. cursor: pointer;
  5305. }
  5306. }
  5307. // 右上角计时状态指示器样式
  5308. .timer-indicator {
  5309. position: fixed;
  5310. z-index: 1000;
  5311. // background: rgba(0, 0, 0, 0.75);
  5312. color: #fff;
  5313. border-radius: 8px;
  5314. padding: 8px 10px;
  5315. display: flex;
  5316. align-items: center;
  5317. gap: 10px;
  5318. // border: 1px solid rgba(255, 255, 255, 0.15);
  5319. .label {
  5320. font-size: 12px;
  5321. opacity: .9;
  5322. margin-right: 2px;
  5323. white-space: nowrap;
  5324. }
  5325. .blocks {
  5326. display: flex;
  5327. align-items: center;
  5328. gap: 8px;
  5329. }
  5330. .block {
  5331. min-width: 45px;
  5332. height: 35px;
  5333. padding: 0 8px;
  5334. border-radius: 6px;
  5335. background: #111;
  5336. display: inline-flex;
  5337. align-items: center;
  5338. justify-content: center;
  5339. font-weight: 700;
  5340. font-size: 22px;
  5341. letter-spacing: 1px;
  5342. }
  5343. .colon {
  5344. position: relative;
  5345. width: 6px;
  5346. display: inline-flex;
  5347. align-items: center;
  5348. justify-content: center;
  5349. }
  5350. .colon::before,
  5351. .colon::after {
  5352. content: '';
  5353. width: 4px;
  5354. height: 4px;
  5355. border-radius: 50%;
  5356. background: #000;
  5357. display: block;
  5358. opacity: .9;
  5359. position: absolute;
  5360. left: 0;
  5361. }
  5362. .colon::before { top: 4px; }
  5363. .colon::after { bottom: 4px; }
  5364. // 全屏尺寸略大
  5365. .pptist-student-viewer.fullscreen & .block {
  5366. min-width: 40px;
  5367. height: 30px;
  5368. font-size: 18px;
  5369. }
  5370. &.countdown .block {
  5371. background: #222;
  5372. }
  5373. &.timeout .block,
  5374. &.timeout .colon {
  5375. background: #ff4d4f;
  5376. color: #fff;
  5377. }
  5378. }
  5379. .viewport {
  5380. position: relative;
  5381. width: 100%;
  5382. height: 100%;
  5383. background-color: #fff;
  5384. }
  5385. .background {
  5386. width: 100%;
  5387. height: 100%;
  5388. background-position: center;
  5389. position: absolute;
  5390. }
  5391. // 响应式设计
  5392. @media (max-width: 768px) {
  5393. .layout-content-left {
  5394. width: 160px;
  5395. }
  5396. .layout-content-right {
  5397. width: 160px;
  5398. }
  5399. .viewer-header {
  5400. padding: 0 16px;
  5401. .slide-title {
  5402. font-size: 16px;
  5403. }
  5404. .viewer-controls button {
  5405. padding: 6px 12px;
  5406. font-size: 14px;
  5407. }
  5408. }
  5409. }
  5410. /* 作业提交按钮样式 */
  5411. .homework-submit-btn {
  5412. position: fixed;
  5413. bottom: 160px;
  5414. z-index: 100;
  5415. background: #191a19;
  5416. color: white;
  5417. padding: 5px 20px;
  5418. border-radius: 5px;
  5419. cursor: pointer;
  5420. display: flex;
  5421. align-items: center;
  5422. gap: 8px;
  5423. border: 2px solid #191a19;
  5424. transition: all 0.3s ease;
  5425. font-size: 16px;
  5426. font-weight: 500;
  5427. &:hover:not(.submitting) {
  5428. transform: translateY(-2px);
  5429. box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
  5430. }
  5431. &:active:not(.submitting) {
  5432. transform: translateY(0);
  5433. }
  5434. &.submitting {
  5435. cursor: not-allowed;
  5436. opacity: 0.8;
  5437. background: linear-gradient(135deg, #999 0%, #666 100%);
  5438. }
  5439. .btn-text {
  5440. white-space: nowrap;
  5441. }
  5442. .tool-btn {
  5443. background: transparent;
  5444. color: white;
  5445. width: 20px;
  5446. height: 20px;
  5447. font-size: 16px;
  5448. &:hover {
  5449. background: transparent;
  5450. transform: none;
  5451. }
  5452. }
  5453. .loading-spinner {
  5454. width: 20px;
  5455. height: 20px;
  5456. border: 2px solid rgba(255, 255, 255, 0.3);
  5457. border-top: 2px solid white;
  5458. border-radius: 50%;
  5459. animation: spin 1s linear infinite;
  5460. }
  5461. }
  5462. /* 刷新网页按钮样式 */
  5463. .refresh-page-btn {
  5464. position: fixed;
  5465. bottom: 160px;
  5466. z-index: 100;
  5467. color: #000;
  5468. padding: 5px 20px;
  5469. border-radius: 5px;
  5470. background: #fff;
  5471. cursor: pointer;
  5472. display: flex;
  5473. align-items: center;
  5474. gap: 8px;
  5475. border: 2px solid #e9e9e9;
  5476. transition: all 0.3s ease;
  5477. font-size: 16px;
  5478. font-weight: 500;
  5479. &:hover {
  5480. transform: translateY(-2px);
  5481. box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
  5482. }
  5483. &:active {
  5484. transform: translateY(0);
  5485. }
  5486. .btn-text {
  5487. white-space: nowrap;
  5488. }
  5489. .tool-btn {
  5490. background: transparent;
  5491. color: #000;
  5492. width: 20px;
  5493. height: 20px;
  5494. font-size: 16px;
  5495. display: flex;
  5496. align-items: center;
  5497. &:hover {
  5498. background: transparent;
  5499. transform: none;
  5500. }
  5501. }
  5502. }
  5503. /* Loading状态样式 */
  5504. .loading-overlay {
  5505. position: absolute;
  5506. top: 0;
  5507. left: 0;
  5508. right: 0;
  5509. bottom: 0;
  5510. background: rgba(255, 255, 255, 0.95);
  5511. display: flex;
  5512. align-items: center;
  5513. justify-content: center;
  5514. z-index: 1000;
  5515. .loading-spinner {
  5516. width: 40px;
  5517. height: 40px;
  5518. border: 4px solid #f3f3f3;
  5519. border-top: 4px solid #1890ff;
  5520. border-radius: 50%;
  5521. animation: spin 1s linear infinite;
  5522. margin: 0 auto 16px;
  5523. }
  5524. }
  5525. .loading-content {
  5526. text-align: center;
  5527. color: #666;
  5528. }
  5529. .loading-text {
  5530. font-size: 14px;
  5531. color: #666;
  5532. }
  5533. @keyframes spin {
  5534. 0% { transform: rotate(0deg); }
  5535. 100% { transform: rotate(360deg); }
  5536. }
  5537. /* 标签页切换器样式 */
  5538. .tab-switcher {
  5539. display: flex;
  5540. flex: 1;
  5541. margin-right: 12px;
  5542. border-bottom: 1px solid #e0e0e0;
  5543. padding-bottom: 0;
  5544. height: 100%;
  5545. justify-content: center;
  5546. gap: 20px;
  5547. }
  5548. .tab-btn {
  5549. // flex: 1;
  5550. // padding: 12px 16px;
  5551. border: none;
  5552. background: transparent;
  5553. color: #666;
  5554. cursor: pointer;
  5555. transition: all 0.2s ease;
  5556. font-size: 14px;
  5557. font-weight: 500;
  5558. text-align: center;
  5559. white-space: nowrap;
  5560. position: relative;
  5561. border-radius: 0;
  5562. &:hover {
  5563. color: #333;
  5564. }
  5565. &.active {
  5566. color: #333;
  5567. font-weight: 600;
  5568. &::after {
  5569. content: '';
  5570. position: absolute;
  5571. bottom: -1px;
  5572. left: 0;
  5573. right: 0;
  5574. height: 2px;
  5575. background: #333;
  5576. border-radius: 1px;
  5577. }
  5578. }
  5579. }
  5580. // 在适当位置添加连接状态指示器
  5581. .connection-status {
  5582. position: fixed;
  5583. top: 10px;
  5584. right: 10px;
  5585. background-color: rgba(255, 255, 255, 0.9);
  5586. border-radius: 5px;
  5587. padding: 5px 10px;
  5588. display: flex;
  5589. align-items: center;
  5590. z-index: 1000;
  5591. .status-indicator {
  5592. // 胶囊浅蓝底 + 蓝色文字
  5593. padding: 5px 12px 5px 22px;
  5594. border-radius: 5px;
  5595. margin-right: 10px;
  5596. display: flex;
  5597. justify-content: center;
  5598. align-items: center;
  5599. position: relative;
  5600. background: transparent; // 根据具体状态设置渐变
  5601. // 边框去除
  5602. // border: 1px solid rgba(59, 111, 255, 0.35);
  5603. box-shadow: 0 2px 8px rgba(59, 111, 255, 0.15);
  5604. // 左侧状态圆点(不同状态不同颜色)
  5605. &::before {
  5606. content: "";
  5607. position: absolute;
  5608. left: 8px;
  5609. width: 8px;
  5610. height: 8px;
  5611. border-radius: 50%;
  5612. background-color: #1890ff; // 默认使用连接中蓝色
  5613. box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.12);
  5614. }
  5615. &.connected::before {
  5616. background-color: #52c41a; // 原始绿色
  5617. box-shadow: 0 0 0 2px rgba(82, 196, 26, 0.18);
  5618. }
  5619. &.connecting::before {
  5620. background-color: #1890ff; // 原始蓝色
  5621. box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.18);
  5622. }
  5623. &.disconnected::before {
  5624. background-color: #ff4d4f; // 原始红色
  5625. box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.18);
  5626. }
  5627. span {
  5628. color: #1890ff; // 默认蓝色,具体状态里覆盖
  5629. font-size: 12px;
  5630. // font-weight: 600;
  5631. letter-spacing: 0.2px;
  5632. }
  5633. // 以原始主色为基础的浅色渐变与文字色
  5634. &.connected {
  5635. background: rgba(82, 196, 26, 0.15);
  5636. span { color: #52c41a; }
  5637. }
  5638. &.connecting {
  5639. background: rgba(24, 144, 255, 0.15);
  5640. span { color: #1890ff; }
  5641. }
  5642. &.disconnected {
  5643. background: rgba(255, 77, 79, 0.15);
  5644. span { color: #ff4d4f; }
  5645. }
  5646. }
  5647. .reconnect-btn {
  5648. background: linear-gradient(180deg, #eaf2ff 0%, #ddebff 100%);
  5649. color: #3b6fff;
  5650. border: none;
  5651. border-radius: 5px;
  5652. padding: 6px 14px;
  5653. cursor: pointer;
  5654. transition: all 0.2s ease;
  5655. // font-weight: 600;
  5656. box-shadow: 0 2px 8px rgba(59, 111, 255, 0.15);
  5657. &:hover {
  5658. background: linear-gradient(180deg, #e2edff 0%, #d3e4ff 100%);
  5659. border-color: rgba(59, 111, 255, 0.55);
  5660. box-shadow: 0 4px 12px rgba(59, 111, 255, 0.2);
  5661. }
  5662. }
  5663. }
  5664. .homework-check-box {
  5665. position: absolute;
  5666. top: 0;
  5667. left: 50%;
  5668. transform: translate(-50%, 0);
  5669. display: flex;
  5670. align-items: center;
  5671. // box-shadow: 0px 3px 4px 3px #f2f2f2;
  5672. padding: 8px;
  5673. border-radius: 0 0 5px 5px;
  5674. background: #fff;
  5675. z-index: 999;
  5676. transition: max-height 0.3s ease, padding 0.3s ease, overflow 0s;
  5677. &.fullscreen-mode {
  5678. overflow: hidden;
  5679. max-height: 5px;
  5680. padding: 0;
  5681. background: #f6c82b;
  5682. border-radius: 0;
  5683. transition: max-height 0.3s ease, padding 0.3s ease;
  5684. cursor: pointer;
  5685. .homework-check-box-item-title{
  5686. display: none;
  5687. }
  5688. &:hover {
  5689. max-height: 80px;
  5690. padding: 8px;
  5691. background: #fff;
  5692. border-radius: 0 0 5px 5px;
  5693. .homework-check-box-item-title{
  5694. display: block;
  5695. }
  5696. }
  5697. &.fs-expanded {
  5698. max-height: 80px;
  5699. padding: 8px;
  5700. background: #fff;
  5701. border-radius: 0 0 5px 5px;
  5702. .homework-check-box-item-title{
  5703. display: block;
  5704. }
  5705. }
  5706. }
  5707. .homework-check-box-item{
  5708. padding: 10px 18px;
  5709. border-radius: 5px;
  5710. font-weight: 600;
  5711. cursor: pointer;
  5712. transition: all 0.3s ease;
  5713. &.active{
  5714. background: #f6c82b;
  5715. }
  5716. &:hover{
  5717. background: #fff;
  5718. color: #f6c82b;
  5719. }
  5720. }
  5721. .homework-check-box-item-title{}
  5722. }
  5723. .aiBtn {
  5724. position: absolute;
  5725. display: flex;
  5726. align-items: center;
  5727. background: #fff;
  5728. z-index: 9999;
  5729. border-radius: 50px;
  5730. border: 3px solid #f6c82b;
  5731. padding: 10px 15px;
  5732. font-weight: 600;
  5733. gap: 5px;
  5734. cursor: move;
  5735. user-select: none;
  5736. touch-action: none; /* 防止触摸设备上的默认行为 */
  5737. box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
  5738. .aiBtn-icon{
  5739. font-size: 16px;
  5740. color: #f6c82b;
  5741. }
  5742. &:hover {
  5743. background: #f9f9f9;
  5744. }
  5745. &:active {
  5746. transform: scale(0.98);
  5747. }
  5748. }
  5749. </style>