index.vue 216 KB

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