pdf_viewer.js 224 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2022 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * JavaScript code in this page
  21. */
  22. (function webpackUniversalModuleDefinition(root, factory) {
  23. if(typeof exports === 'object' && typeof module === 'object')
  24. module.exports = factory();
  25. else if(typeof define === 'function' && define.amd)
  26. define("pdfjs-dist/web/pdf_viewer", [], factory);
  27. else if(typeof exports === 'object')
  28. exports["pdfjs-dist/web/pdf_viewer"] = factory();
  29. else
  30. root["pdfjs-dist/web/pdf_viewer"] = root.pdfjsViewer = factory();
  31. })(globalThis, () => {
  32. return /******/ (() => { // webpackBootstrap
  33. /******/ "use strict";
  34. /******/ var __webpack_modules__ = ([
  35. /* 0 */,
  36. /* 1 */
  37. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  38. Object.defineProperty(exports, "__esModule", ({
  39. value: true
  40. }));
  41. exports.DefaultXfaLayerFactory = exports.DefaultTextLayerFactory = exports.DefaultStructTreeLayerFactory = exports.DefaultAnnotationLayerFactory = exports.DefaultAnnotationEditorLayerFactory = void 0;
  42. var _annotation_editor_layer_builder = __w_pdfjs_require__(2);
  43. var _annotation_layer_builder = __w_pdfjs_require__(5);
  44. var _l10n_utils = __w_pdfjs_require__(4);
  45. var _pdf_link_service = __w_pdfjs_require__(7);
  46. var _struct_tree_layer_builder = __w_pdfjs_require__(8);
  47. var _text_layer_builder = __w_pdfjs_require__(9);
  48. var _xfa_layer_builder = __w_pdfjs_require__(10);
  49. class DefaultAnnotationLayerFactory {
  50. createAnnotationLayerBuilder({
  51. pageDiv,
  52. pdfPage,
  53. annotationStorage = null,
  54. imageResourcesPath = "",
  55. renderForms = true,
  56. l10n = _l10n_utils.NullL10n,
  57. enableScripting = false,
  58. hasJSActionsPromise = null,
  59. mouseState = null,
  60. fieldObjectsPromise = null,
  61. annotationCanvasMap = null,
  62. accessibilityManager = null
  63. }) {
  64. return new _annotation_layer_builder.AnnotationLayerBuilder({
  65. pageDiv,
  66. pdfPage,
  67. imageResourcesPath,
  68. renderForms,
  69. linkService: new _pdf_link_service.SimpleLinkService(),
  70. l10n,
  71. annotationStorage,
  72. enableScripting,
  73. hasJSActionsPromise,
  74. fieldObjectsPromise,
  75. mouseState,
  76. annotationCanvasMap,
  77. accessibilityManager
  78. });
  79. }
  80. }
  81. exports.DefaultAnnotationLayerFactory = DefaultAnnotationLayerFactory;
  82. class DefaultAnnotationEditorLayerFactory {
  83. createAnnotationEditorLayerBuilder({
  84. uiManager = null,
  85. pageDiv,
  86. pdfPage,
  87. accessibilityManager = null,
  88. l10n,
  89. annotationStorage = null
  90. }) {
  91. return new _annotation_editor_layer_builder.AnnotationEditorLayerBuilder({
  92. uiManager,
  93. pageDiv,
  94. pdfPage,
  95. accessibilityManager,
  96. l10n,
  97. annotationStorage
  98. });
  99. }
  100. }
  101. exports.DefaultAnnotationEditorLayerFactory = DefaultAnnotationEditorLayerFactory;
  102. class DefaultStructTreeLayerFactory {
  103. createStructTreeLayerBuilder({
  104. pdfPage
  105. }) {
  106. return new _struct_tree_layer_builder.StructTreeLayerBuilder({
  107. pdfPage
  108. });
  109. }
  110. }
  111. exports.DefaultStructTreeLayerFactory = DefaultStructTreeLayerFactory;
  112. class DefaultTextLayerFactory {
  113. createTextLayerBuilder({
  114. textLayerDiv,
  115. pageIndex,
  116. viewport,
  117. eventBus,
  118. highlighter,
  119. accessibilityManager = null
  120. }) {
  121. return new _text_layer_builder.TextLayerBuilder({
  122. textLayerDiv,
  123. pageIndex,
  124. viewport,
  125. eventBus,
  126. highlighter,
  127. accessibilityManager
  128. });
  129. }
  130. }
  131. exports.DefaultTextLayerFactory = DefaultTextLayerFactory;
  132. class DefaultXfaLayerFactory {
  133. createXfaLayerBuilder({
  134. pageDiv,
  135. pdfPage,
  136. annotationStorage = null
  137. }) {
  138. return new _xfa_layer_builder.XfaLayerBuilder({
  139. pageDiv,
  140. pdfPage,
  141. annotationStorage,
  142. linkService: new _pdf_link_service.SimpleLinkService()
  143. });
  144. }
  145. }
  146. exports.DefaultXfaLayerFactory = DefaultXfaLayerFactory;
  147. /***/ }),
  148. /* 2 */
  149. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  150. Object.defineProperty(exports, "__esModule", ({
  151. value: true
  152. }));
  153. exports.AnnotationEditorLayerBuilder = void 0;
  154. var _pdfjsLib = __w_pdfjs_require__(3);
  155. var _l10n_utils = __w_pdfjs_require__(4);
  156. class AnnotationEditorLayerBuilder {
  157. #uiManager;
  158. constructor(options) {
  159. this.pageDiv = options.pageDiv;
  160. this.pdfPage = options.pdfPage;
  161. this.annotationStorage = options.annotationStorage || null;
  162. this.accessibilityManager = options.accessibilityManager;
  163. this.l10n = options.l10n || _l10n_utils.NullL10n;
  164. this.annotationEditorLayer = null;
  165. this.div = null;
  166. this._cancelled = false;
  167. this.#uiManager = options.uiManager;
  168. }
  169. async render(viewport, intent = "display") {
  170. if (intent !== "display") {
  171. return;
  172. }
  173. if (this._cancelled) {
  174. return;
  175. }
  176. const clonedViewport = viewport.clone({
  177. dontFlip: true
  178. });
  179. if (this.div) {
  180. this.annotationEditorLayer.update({
  181. viewport: clonedViewport
  182. });
  183. this.show();
  184. return;
  185. }
  186. this.div = document.createElement("div");
  187. this.div.className = "annotationEditorLayer";
  188. this.div.tabIndex = 0;
  189. this.pageDiv.append(this.div);
  190. this.annotationEditorLayer = new _pdfjsLib.AnnotationEditorLayer({
  191. uiManager: this.#uiManager,
  192. div: this.div,
  193. annotationStorage: this.annotationStorage,
  194. accessibilityManager: this.accessibilityManager,
  195. pageIndex: this.pdfPage._pageIndex,
  196. l10n: this.l10n,
  197. viewport: clonedViewport
  198. });
  199. const parameters = {
  200. viewport: clonedViewport,
  201. div: this.div,
  202. annotations: null,
  203. intent
  204. };
  205. this.annotationEditorLayer.render(parameters);
  206. }
  207. cancel() {
  208. this._cancelled = true;
  209. this.destroy();
  210. }
  211. hide() {
  212. if (!this.div) {
  213. return;
  214. }
  215. this.div.hidden = true;
  216. }
  217. show() {
  218. if (!this.div) {
  219. return;
  220. }
  221. this.div.hidden = false;
  222. }
  223. destroy() {
  224. if (!this.div) {
  225. return;
  226. }
  227. this.pageDiv = null;
  228. this.annotationEditorLayer.destroy();
  229. this.div.remove();
  230. }
  231. }
  232. exports.AnnotationEditorLayerBuilder = AnnotationEditorLayerBuilder;
  233. /***/ }),
  234. /* 3 */
  235. /***/ ((module) => {
  236. let pdfjsLib;
  237. if (typeof window !== "undefined" && window["pdfjs-dist/build/pdf"]) {
  238. pdfjsLib = window["pdfjs-dist/build/pdf"];
  239. } else {
  240. pdfjsLib = require("../build/pdf.js");
  241. }
  242. module.exports = pdfjsLib;
  243. /***/ }),
  244. /* 4 */
  245. /***/ ((__unused_webpack_module, exports) => {
  246. Object.defineProperty(exports, "__esModule", ({
  247. value: true
  248. }));
  249. exports.NullL10n = void 0;
  250. exports.fixupLangCode = fixupLangCode;
  251. exports.getL10nFallback = getL10nFallback;
  252. const DEFAULT_L10N_STRINGS = {
  253. of_pages: "of {{pagesCount}}",
  254. page_of_pages: "({{pageNumber}} of {{pagesCount}})",
  255. document_properties_kb: "{{size_kb}} KB ({{size_b}} bytes)",
  256. document_properties_mb: "{{size_mb}} MB ({{size_b}} bytes)",
  257. document_properties_date_string: "{{date}}, {{time}}",
  258. document_properties_page_size_unit_inches: "in",
  259. document_properties_page_size_unit_millimeters: "mm",
  260. document_properties_page_size_orientation_portrait: "portrait",
  261. document_properties_page_size_orientation_landscape: "landscape",
  262. document_properties_page_size_name_a3: "A3",
  263. document_properties_page_size_name_a4: "A4",
  264. document_properties_page_size_name_letter: "Letter",
  265. document_properties_page_size_name_legal: "Legal",
  266. document_properties_page_size_dimension_string: "{{width}} × {{height}} {{unit}} ({{orientation}})",
  267. document_properties_page_size_dimension_name_string: "{{width}} × {{height}} {{unit}} ({{name}}, {{orientation}})",
  268. document_properties_linearized_yes: "Yes",
  269. document_properties_linearized_no: "No",
  270. additional_layers: "Additional Layers",
  271. page_landmark: "Page {{page}}",
  272. thumb_page_title: "Page {{page}}",
  273. thumb_page_canvas: "Thumbnail of Page {{page}}",
  274. find_reached_top: "Reached top of document, continued from bottom",
  275. find_reached_bottom: "Reached end of document, continued from top",
  276. "find_match_count[one]": "{{current}} of {{total}} match",
  277. "find_match_count[other]": "{{current}} of {{total}} matches",
  278. "find_match_count_limit[one]": "More than {{limit}} match",
  279. "find_match_count_limit[other]": "More than {{limit}} matches",
  280. find_not_found: "Phrase not found",
  281. page_scale_width: "Page Width",
  282. page_scale_fit: "Page Fit",
  283. page_scale_auto: "Automatic Zoom",
  284. page_scale_actual: "Actual Size",
  285. page_scale_percent: "{{scale}}%",
  286. loading: "Loading…",
  287. loading_error: "An error occurred while loading the PDF.",
  288. invalid_file_error: "Invalid or corrupted PDF file.",
  289. missing_file_error: "Missing PDF file.",
  290. unexpected_response_error: "Unexpected server response.",
  291. rendering_error: "An error occurred while rendering the page.",
  292. printing_not_supported: "Warning: Printing is not fully supported by this browser.",
  293. printing_not_ready: "Warning: The PDF is not fully loaded for printing.",
  294. web_fonts_disabled: "Web fonts are disabled: unable to use embedded PDF fonts.",
  295. free_text2_default_content: "Start typing…",
  296. editor_free_text2_aria_label: "Text Editor",
  297. editor_ink2_aria_label: "Draw Editor",
  298. editor_ink_canvas_aria_label: "User-created image"
  299. };
  300. {
  301. DEFAULT_L10N_STRINGS.print_progress_percent = "{{progress}}%";
  302. }
  303. function getL10nFallback(key, args) {
  304. switch (key) {
  305. case "find_match_count":
  306. key = `find_match_count[${args.total === 1 ? "one" : "other"}]`;
  307. break;
  308. case "find_match_count_limit":
  309. key = `find_match_count_limit[${args.limit === 1 ? "one" : "other"}]`;
  310. break;
  311. }
  312. return DEFAULT_L10N_STRINGS[key] || "";
  313. }
  314. const PARTIAL_LANG_CODES = {
  315. en: "en-US",
  316. es: "es-ES",
  317. fy: "fy-NL",
  318. ga: "ga-IE",
  319. gu: "gu-IN",
  320. hi: "hi-IN",
  321. hy: "hy-AM",
  322. nb: "nb-NO",
  323. ne: "ne-NP",
  324. nn: "nn-NO",
  325. pa: "pa-IN",
  326. pt: "pt-PT",
  327. sv: "sv-SE",
  328. zh: "zh-CN"
  329. };
  330. function fixupLangCode(langCode) {
  331. return PARTIAL_LANG_CODES[langCode?.toLowerCase()] || langCode;
  332. }
  333. function formatL10nValue(text, args) {
  334. if (!args) {
  335. return text;
  336. }
  337. return text.replace(/\{\{\s*(\w+)\s*\}\}/g, (all, name) => {
  338. return name in args ? args[name] : "{{" + name + "}}";
  339. });
  340. }
  341. const NullL10n = {
  342. async getLanguage() {
  343. return "en-us";
  344. },
  345. async getDirection() {
  346. return "ltr";
  347. },
  348. async get(key, args = null, fallback = getL10nFallback(key, args)) {
  349. return formatL10nValue(fallback, args);
  350. },
  351. async translate(element) {}
  352. };
  353. exports.NullL10n = NullL10n;
  354. /***/ }),
  355. /* 5 */
  356. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  357. Object.defineProperty(exports, "__esModule", ({
  358. value: true
  359. }));
  360. exports.AnnotationLayerBuilder = void 0;
  361. var _pdfjsLib = __w_pdfjs_require__(3);
  362. var _l10n_utils = __w_pdfjs_require__(4);
  363. var _ui_utils = __w_pdfjs_require__(6);
  364. class AnnotationLayerBuilder {
  365. #onPresentationModeChanged = null;
  366. constructor({
  367. pageDiv,
  368. pdfPage,
  369. linkService,
  370. downloadManager,
  371. annotationStorage = null,
  372. imageResourcesPath = "",
  373. renderForms = true,
  374. l10n = _l10n_utils.NullL10n,
  375. enableScripting = false,
  376. hasJSActionsPromise = null,
  377. fieldObjectsPromise = null,
  378. mouseState = null,
  379. annotationCanvasMap = null,
  380. accessibilityManager = null
  381. }) {
  382. this.pageDiv = pageDiv;
  383. this.pdfPage = pdfPage;
  384. this.linkService = linkService;
  385. this.downloadManager = downloadManager;
  386. this.imageResourcesPath = imageResourcesPath;
  387. this.renderForms = renderForms;
  388. this.l10n = l10n;
  389. this.annotationStorage = annotationStorage;
  390. this.enableScripting = enableScripting;
  391. this._hasJSActionsPromise = hasJSActionsPromise;
  392. this._fieldObjectsPromise = fieldObjectsPromise;
  393. this._mouseState = mouseState;
  394. this._annotationCanvasMap = annotationCanvasMap;
  395. this._accessibilityManager = accessibilityManager;
  396. this.div = null;
  397. this._cancelled = false;
  398. this._eventBus = linkService.eventBus;
  399. }
  400. async render(viewport, intent = "display") {
  401. const [annotations, hasJSActions = false, fieldObjects = null] = await Promise.all([this.pdfPage.getAnnotations({
  402. intent
  403. }), this._hasJSActionsPromise, this._fieldObjectsPromise]);
  404. if (this._cancelled || annotations.length === 0) {
  405. return;
  406. }
  407. const parameters = {
  408. viewport: viewport.clone({
  409. dontFlip: true
  410. }),
  411. div: this.div,
  412. annotations,
  413. page: this.pdfPage,
  414. imageResourcesPath: this.imageResourcesPath,
  415. renderForms: this.renderForms,
  416. linkService: this.linkService,
  417. downloadManager: this.downloadManager,
  418. annotationStorage: this.annotationStorage,
  419. enableScripting: this.enableScripting,
  420. hasJSActions,
  421. fieldObjects,
  422. mouseState: this._mouseState,
  423. annotationCanvasMap: this._annotationCanvasMap,
  424. accessibilityManager: this._accessibilityManager
  425. };
  426. if (this.div) {
  427. _pdfjsLib.AnnotationLayer.update(parameters);
  428. } else {
  429. this.div = document.createElement("div");
  430. this.div.className = "annotationLayer";
  431. this.pageDiv.append(this.div);
  432. parameters.div = this.div;
  433. _pdfjsLib.AnnotationLayer.render(parameters);
  434. this.l10n.translate(this.div);
  435. if (this.linkService.isInPresentationMode) {
  436. this.#updatePresentationModeState(_ui_utils.PresentationModeState.FULLSCREEN);
  437. }
  438. if (!this.#onPresentationModeChanged) {
  439. this.#onPresentationModeChanged = evt => {
  440. this.#updatePresentationModeState(evt.state);
  441. };
  442. this._eventBus?._on("presentationmodechanged", this.#onPresentationModeChanged);
  443. }
  444. }
  445. }
  446. cancel() {
  447. this._cancelled = true;
  448. if (this.#onPresentationModeChanged) {
  449. this._eventBus?._off("presentationmodechanged", this.#onPresentationModeChanged);
  450. this.#onPresentationModeChanged = null;
  451. }
  452. }
  453. hide() {
  454. if (!this.div) {
  455. return;
  456. }
  457. this.div.hidden = true;
  458. }
  459. #updatePresentationModeState(state) {
  460. if (!this.div) {
  461. return;
  462. }
  463. let disableFormElements = false;
  464. switch (state) {
  465. case _ui_utils.PresentationModeState.FULLSCREEN:
  466. disableFormElements = true;
  467. break;
  468. case _ui_utils.PresentationModeState.NORMAL:
  469. break;
  470. default:
  471. return;
  472. }
  473. for (const section of this.div.childNodes) {
  474. if (section.hasAttribute("data-internal-link")) {
  475. continue;
  476. }
  477. section.inert = disableFormElements;
  478. }
  479. }
  480. }
  481. exports.AnnotationLayerBuilder = AnnotationLayerBuilder;
  482. /***/ }),
  483. /* 6 */
  484. /***/ ((__unused_webpack_module, exports) => {
  485. Object.defineProperty(exports, "__esModule", ({
  486. value: true
  487. }));
  488. exports.animationStarted = exports.VERTICAL_PADDING = exports.UNKNOWN_SCALE = exports.TextLayerMode = exports.SpreadMode = exports.SidebarView = exports.ScrollMode = exports.SCROLLBAR_PADDING = exports.RenderingStates = exports.RendererType = exports.ProgressBar = exports.PresentationModeState = exports.OutputScale = exports.MIN_SCALE = exports.MAX_SCALE = exports.MAX_AUTO_SCALE = exports.DEFAULT_SCALE_VALUE = exports.DEFAULT_SCALE_DELTA = exports.DEFAULT_SCALE = exports.AutoPrintRegExp = void 0;
  489. exports.apiPageLayoutToViewerModes = apiPageLayoutToViewerModes;
  490. exports.apiPageModeToSidebarView = apiPageModeToSidebarView;
  491. exports.approximateFraction = approximateFraction;
  492. exports.backtrackBeforeAllVisibleElements = backtrackBeforeAllVisibleElements;
  493. exports.binarySearchFirstItem = binarySearchFirstItem;
  494. exports.docStyle = void 0;
  495. exports.getActiveOrFocusedElement = getActiveOrFocusedElement;
  496. exports.getPageSizeInches = getPageSizeInches;
  497. exports.getVisibleElements = getVisibleElements;
  498. exports.isPortraitOrientation = isPortraitOrientation;
  499. exports.isValidRotation = isValidRotation;
  500. exports.isValidScrollMode = isValidScrollMode;
  501. exports.isValidSpreadMode = isValidSpreadMode;
  502. exports.noContextMenuHandler = noContextMenuHandler;
  503. exports.normalizeWheelEventDelta = normalizeWheelEventDelta;
  504. exports.normalizeWheelEventDirection = normalizeWheelEventDirection;
  505. exports.parseQueryString = parseQueryString;
  506. exports.removeNullCharacters = removeNullCharacters;
  507. exports.roundToDivide = roundToDivide;
  508. exports.scrollIntoView = scrollIntoView;
  509. exports.watchScroll = watchScroll;
  510. const DEFAULT_SCALE_VALUE = "auto";
  511. exports.DEFAULT_SCALE_VALUE = DEFAULT_SCALE_VALUE;
  512. const DEFAULT_SCALE = 1.0;
  513. exports.DEFAULT_SCALE = DEFAULT_SCALE;
  514. const DEFAULT_SCALE_DELTA = 1.1;
  515. exports.DEFAULT_SCALE_DELTA = DEFAULT_SCALE_DELTA;
  516. const MIN_SCALE = 0.1;
  517. exports.MIN_SCALE = MIN_SCALE;
  518. const MAX_SCALE = 10.0;
  519. exports.MAX_SCALE = MAX_SCALE;
  520. const UNKNOWN_SCALE = 0;
  521. exports.UNKNOWN_SCALE = UNKNOWN_SCALE;
  522. const MAX_AUTO_SCALE = 1.25;
  523. exports.MAX_AUTO_SCALE = MAX_AUTO_SCALE;
  524. const SCROLLBAR_PADDING = 40;
  525. exports.SCROLLBAR_PADDING = SCROLLBAR_PADDING;
  526. const VERTICAL_PADDING = 5;
  527. exports.VERTICAL_PADDING = VERTICAL_PADDING;
  528. const RenderingStates = {
  529. INITIAL: 0,
  530. RUNNING: 1,
  531. PAUSED: 2,
  532. FINISHED: 3
  533. };
  534. exports.RenderingStates = RenderingStates;
  535. const PresentationModeState = {
  536. UNKNOWN: 0,
  537. NORMAL: 1,
  538. CHANGING: 2,
  539. FULLSCREEN: 3
  540. };
  541. exports.PresentationModeState = PresentationModeState;
  542. const SidebarView = {
  543. UNKNOWN: -1,
  544. NONE: 0,
  545. THUMBS: 1,
  546. OUTLINE: 2,
  547. ATTACHMENTS: 3,
  548. LAYERS: 4
  549. };
  550. exports.SidebarView = SidebarView;
  551. const RendererType = {
  552. CANVAS: "canvas",
  553. SVG: "svg"
  554. };
  555. exports.RendererType = RendererType;
  556. const TextLayerMode = {
  557. DISABLE: 0,
  558. ENABLE: 1
  559. };
  560. exports.TextLayerMode = TextLayerMode;
  561. const ScrollMode = {
  562. UNKNOWN: -1,
  563. VERTICAL: 0,
  564. HORIZONTAL: 1,
  565. WRAPPED: 2,
  566. PAGE: 3
  567. };
  568. exports.ScrollMode = ScrollMode;
  569. const SpreadMode = {
  570. UNKNOWN: -1,
  571. NONE: 0,
  572. ODD: 1,
  573. EVEN: 2
  574. };
  575. exports.SpreadMode = SpreadMode;
  576. const AutoPrintRegExp = /\bprint\s*\(/;
  577. exports.AutoPrintRegExp = AutoPrintRegExp;
  578. class OutputScale {
  579. constructor() {
  580. const pixelRatio = window.devicePixelRatio || 1;
  581. this.sx = pixelRatio;
  582. this.sy = pixelRatio;
  583. }
  584. get scaled() {
  585. return this.sx !== 1 || this.sy !== 1;
  586. }
  587. }
  588. exports.OutputScale = OutputScale;
  589. function scrollIntoView(element, spot, scrollMatches = false) {
  590. let parent = element.offsetParent;
  591. if (!parent) {
  592. console.error("offsetParent is not set -- cannot scroll");
  593. return;
  594. }
  595. let offsetY = element.offsetTop + element.clientTop;
  596. let offsetX = element.offsetLeft + element.clientLeft;
  597. while (parent.clientHeight === parent.scrollHeight && parent.clientWidth === parent.scrollWidth || scrollMatches && (parent.classList.contains("markedContent") || getComputedStyle(parent).overflow === "hidden")) {
  598. offsetY += parent.offsetTop;
  599. offsetX += parent.offsetLeft;
  600. parent = parent.offsetParent;
  601. if (!parent) {
  602. return;
  603. }
  604. }
  605. if (spot) {
  606. if (spot.top !== undefined) {
  607. offsetY += spot.top;
  608. }
  609. if (spot.left !== undefined) {
  610. offsetX += spot.left;
  611. parent.scrollLeft = offsetX;
  612. }
  613. }
  614. parent.scrollTop = offsetY;
  615. }
  616. function watchScroll(viewAreaElement, callback) {
  617. const debounceScroll = function (evt) {
  618. if (rAF) {
  619. return;
  620. }
  621. rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {
  622. rAF = null;
  623. const currentX = viewAreaElement.scrollLeft;
  624. const lastX = state.lastX;
  625. if (currentX !== lastX) {
  626. state.right = currentX > lastX;
  627. }
  628. state.lastX = currentX;
  629. const currentY = viewAreaElement.scrollTop;
  630. const lastY = state.lastY;
  631. if (currentY !== lastY) {
  632. state.down = currentY > lastY;
  633. }
  634. state.lastY = currentY;
  635. callback(state);
  636. });
  637. };
  638. const state = {
  639. right: true,
  640. down: true,
  641. lastX: viewAreaElement.scrollLeft,
  642. lastY: viewAreaElement.scrollTop,
  643. _eventHandler: debounceScroll
  644. };
  645. let rAF = null;
  646. viewAreaElement.addEventListener("scroll", debounceScroll, true);
  647. return state;
  648. }
  649. function parseQueryString(query) {
  650. const params = new Map();
  651. for (const [key, value] of new URLSearchParams(query)) {
  652. params.set(key.toLowerCase(), value);
  653. }
  654. return params;
  655. }
  656. const NullCharactersRegExp = /\x00/g;
  657. const InvisibleCharactersRegExp = /[\x01-\x1F]/g;
  658. function removeNullCharacters(str, replaceInvisible = false) {
  659. if (typeof str !== "string") {
  660. console.error(`The argument must be a string.`);
  661. return str;
  662. }
  663. if (replaceInvisible) {
  664. str = str.replace(InvisibleCharactersRegExp, " ");
  665. }
  666. return str.replace(NullCharactersRegExp, "");
  667. }
  668. function binarySearchFirstItem(items, condition, start = 0) {
  669. let minIndex = start;
  670. let maxIndex = items.length - 1;
  671. if (maxIndex < 0 || !condition(items[maxIndex])) {
  672. return items.length;
  673. }
  674. if (condition(items[minIndex])) {
  675. return minIndex;
  676. }
  677. while (minIndex < maxIndex) {
  678. const currentIndex = minIndex + maxIndex >> 1;
  679. const currentItem = items[currentIndex];
  680. if (condition(currentItem)) {
  681. maxIndex = currentIndex;
  682. } else {
  683. minIndex = currentIndex + 1;
  684. }
  685. }
  686. return minIndex;
  687. }
  688. function approximateFraction(x) {
  689. if (Math.floor(x) === x) {
  690. return [x, 1];
  691. }
  692. const xinv = 1 / x;
  693. const limit = 8;
  694. if (xinv > limit) {
  695. return [1, limit];
  696. } else if (Math.floor(xinv) === xinv) {
  697. return [1, xinv];
  698. }
  699. const x_ = x > 1 ? xinv : x;
  700. let a = 0,
  701. b = 1,
  702. c = 1,
  703. d = 1;
  704. while (true) {
  705. const p = a + c,
  706. q = b + d;
  707. if (q > limit) {
  708. break;
  709. }
  710. if (x_ <= p / q) {
  711. c = p;
  712. d = q;
  713. } else {
  714. a = p;
  715. b = q;
  716. }
  717. }
  718. let result;
  719. if (x_ - a / b < c / d - x_) {
  720. result = x_ === x ? [a, b] : [b, a];
  721. } else {
  722. result = x_ === x ? [c, d] : [d, c];
  723. }
  724. return result;
  725. }
  726. function roundToDivide(x, div) {
  727. const r = x % div;
  728. return r === 0 ? x : Math.round(x - r + div);
  729. }
  730. function getPageSizeInches({
  731. view,
  732. userUnit,
  733. rotate
  734. }) {
  735. const [x1, y1, x2, y2] = view;
  736. const changeOrientation = rotate % 180 !== 0;
  737. const width = (x2 - x1) / 72 * userUnit;
  738. const height = (y2 - y1) / 72 * userUnit;
  739. return {
  740. width: changeOrientation ? height : width,
  741. height: changeOrientation ? width : height
  742. };
  743. }
  744. function backtrackBeforeAllVisibleElements(index, views, top) {
  745. if (index < 2) {
  746. return index;
  747. }
  748. let elt = views[index].div;
  749. let pageTop = elt.offsetTop + elt.clientTop;
  750. if (pageTop >= top) {
  751. elt = views[index - 1].div;
  752. pageTop = elt.offsetTop + elt.clientTop;
  753. }
  754. for (let i = index - 2; i >= 0; --i) {
  755. elt = views[i].div;
  756. if (elt.offsetTop + elt.clientTop + elt.clientHeight <= pageTop) {
  757. break;
  758. }
  759. index = i;
  760. }
  761. return index;
  762. }
  763. function getVisibleElements({
  764. scrollEl,
  765. views,
  766. sortByVisibility = false,
  767. horizontal = false,
  768. rtl = false
  769. }) {
  770. const top = scrollEl.scrollTop,
  771. bottom = top + scrollEl.clientHeight;
  772. const left = scrollEl.scrollLeft,
  773. right = left + scrollEl.clientWidth;
  774. function isElementBottomAfterViewTop(view) {
  775. const element = view.div;
  776. const elementBottom = element.offsetTop + element.clientTop + element.clientHeight;
  777. return elementBottom > top;
  778. }
  779. function isElementNextAfterViewHorizontally(view) {
  780. const element = view.div;
  781. const elementLeft = element.offsetLeft + element.clientLeft;
  782. const elementRight = elementLeft + element.clientWidth;
  783. return rtl ? elementLeft < right : elementRight > left;
  784. }
  785. const visible = [],
  786. ids = new Set(),
  787. numViews = views.length;
  788. let firstVisibleElementInd = binarySearchFirstItem(views, horizontal ? isElementNextAfterViewHorizontally : isElementBottomAfterViewTop);
  789. if (firstVisibleElementInd > 0 && firstVisibleElementInd < numViews && !horizontal) {
  790. firstVisibleElementInd = backtrackBeforeAllVisibleElements(firstVisibleElementInd, views, top);
  791. }
  792. let lastEdge = horizontal ? right : -1;
  793. for (let i = firstVisibleElementInd; i < numViews; i++) {
  794. const view = views[i],
  795. element = view.div;
  796. const currentWidth = element.offsetLeft + element.clientLeft;
  797. const currentHeight = element.offsetTop + element.clientTop;
  798. const viewWidth = element.clientWidth,
  799. viewHeight = element.clientHeight;
  800. const viewRight = currentWidth + viewWidth;
  801. const viewBottom = currentHeight + viewHeight;
  802. if (lastEdge === -1) {
  803. if (viewBottom >= bottom) {
  804. lastEdge = viewBottom;
  805. }
  806. } else if ((horizontal ? currentWidth : currentHeight) > lastEdge) {
  807. break;
  808. }
  809. if (viewBottom <= top || currentHeight >= bottom || viewRight <= left || currentWidth >= right) {
  810. continue;
  811. }
  812. const hiddenHeight = Math.max(0, top - currentHeight) + Math.max(0, viewBottom - bottom);
  813. const hiddenWidth = Math.max(0, left - currentWidth) + Math.max(0, viewRight - right);
  814. const fractionHeight = (viewHeight - hiddenHeight) / viewHeight,
  815. fractionWidth = (viewWidth - hiddenWidth) / viewWidth;
  816. const percent = fractionHeight * fractionWidth * 100 | 0;
  817. visible.push({
  818. id: view.id,
  819. x: currentWidth,
  820. y: currentHeight,
  821. view,
  822. percent,
  823. widthPercent: fractionWidth * 100 | 0
  824. });
  825. ids.add(view.id);
  826. }
  827. const first = visible[0],
  828. last = visible.at(-1);
  829. if (sortByVisibility) {
  830. visible.sort(function (a, b) {
  831. const pc = a.percent - b.percent;
  832. if (Math.abs(pc) > 0.001) {
  833. return -pc;
  834. }
  835. return a.id - b.id;
  836. });
  837. }
  838. return {
  839. first,
  840. last,
  841. views: visible,
  842. ids
  843. };
  844. }
  845. function noContextMenuHandler(evt) {
  846. evt.preventDefault();
  847. }
  848. function normalizeWheelEventDirection(evt) {
  849. let delta = Math.hypot(evt.deltaX, evt.deltaY);
  850. const angle = Math.atan2(evt.deltaY, evt.deltaX);
  851. if (-0.25 * Math.PI < angle && angle < 0.75 * Math.PI) {
  852. delta = -delta;
  853. }
  854. return delta;
  855. }
  856. function normalizeWheelEventDelta(evt) {
  857. let delta = normalizeWheelEventDirection(evt);
  858. const MOUSE_DOM_DELTA_PIXEL_MODE = 0;
  859. const MOUSE_DOM_DELTA_LINE_MODE = 1;
  860. const MOUSE_PIXELS_PER_LINE = 30;
  861. const MOUSE_LINES_PER_PAGE = 30;
  862. if (evt.deltaMode === MOUSE_DOM_DELTA_PIXEL_MODE) {
  863. delta /= MOUSE_PIXELS_PER_LINE * MOUSE_LINES_PER_PAGE;
  864. } else if (evt.deltaMode === MOUSE_DOM_DELTA_LINE_MODE) {
  865. delta /= MOUSE_LINES_PER_PAGE;
  866. }
  867. return delta;
  868. }
  869. function isValidRotation(angle) {
  870. return Number.isInteger(angle) && angle % 90 === 0;
  871. }
  872. function isValidScrollMode(mode) {
  873. return Number.isInteger(mode) && Object.values(ScrollMode).includes(mode) && mode !== ScrollMode.UNKNOWN;
  874. }
  875. function isValidSpreadMode(mode) {
  876. return Number.isInteger(mode) && Object.values(SpreadMode).includes(mode) && mode !== SpreadMode.UNKNOWN;
  877. }
  878. function isPortraitOrientation(size) {
  879. return size.width <= size.height;
  880. }
  881. const animationStarted = new Promise(function (resolve) {
  882. window.requestAnimationFrame(resolve);
  883. });
  884. exports.animationStarted = animationStarted;
  885. const docStyle = document.documentElement.style;
  886. exports.docStyle = docStyle;
  887. function clamp(v, min, max) {
  888. return Math.min(Math.max(v, min), max);
  889. }
  890. class ProgressBar {
  891. #classList = null;
  892. #percent = 0;
  893. #visible = true;
  894. constructor(id) {
  895. const bar = document.getElementById(id);
  896. this.#classList = bar.classList;
  897. }
  898. get percent() {
  899. return this.#percent;
  900. }
  901. set percent(val) {
  902. this.#percent = clamp(val, 0, 100);
  903. if (isNaN(val)) {
  904. this.#classList.add("indeterminate");
  905. return;
  906. }
  907. this.#classList.remove("indeterminate");
  908. docStyle.setProperty("--progressBar-percent", `${this.#percent}%`);
  909. }
  910. setWidth(viewer) {
  911. if (!viewer) {
  912. return;
  913. }
  914. const container = viewer.parentNode;
  915. const scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
  916. if (scrollbarWidth > 0) {
  917. docStyle.setProperty("--progressBar-end-offset", `${scrollbarWidth}px`);
  918. }
  919. }
  920. hide() {
  921. if (!this.#visible) {
  922. return;
  923. }
  924. this.#visible = false;
  925. this.#classList.add("hidden");
  926. }
  927. show() {
  928. if (this.#visible) {
  929. return;
  930. }
  931. this.#visible = true;
  932. this.#classList.remove("hidden");
  933. }
  934. }
  935. exports.ProgressBar = ProgressBar;
  936. function getActiveOrFocusedElement() {
  937. let curRoot = document;
  938. let curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(":focus");
  939. while (curActiveOrFocused?.shadowRoot) {
  940. curRoot = curActiveOrFocused.shadowRoot;
  941. curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(":focus");
  942. }
  943. return curActiveOrFocused;
  944. }
  945. function apiPageLayoutToViewerModes(layout) {
  946. let scrollMode = ScrollMode.VERTICAL,
  947. spreadMode = SpreadMode.NONE;
  948. switch (layout) {
  949. case "SinglePage":
  950. scrollMode = ScrollMode.PAGE;
  951. break;
  952. case "OneColumn":
  953. break;
  954. case "TwoPageLeft":
  955. scrollMode = ScrollMode.PAGE;
  956. case "TwoColumnLeft":
  957. spreadMode = SpreadMode.ODD;
  958. break;
  959. case "TwoPageRight":
  960. scrollMode = ScrollMode.PAGE;
  961. case "TwoColumnRight":
  962. spreadMode = SpreadMode.EVEN;
  963. break;
  964. }
  965. return {
  966. scrollMode,
  967. spreadMode
  968. };
  969. }
  970. function apiPageModeToSidebarView(mode) {
  971. switch (mode) {
  972. case "UseNone":
  973. return SidebarView.NONE;
  974. case "UseThumbs":
  975. return SidebarView.THUMBS;
  976. case "UseOutlines":
  977. return SidebarView.OUTLINE;
  978. case "UseAttachments":
  979. return SidebarView.ATTACHMENTS;
  980. case "UseOC":
  981. return SidebarView.LAYERS;
  982. }
  983. return SidebarView.NONE;
  984. }
  985. /***/ }),
  986. /* 7 */
  987. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  988. Object.defineProperty(exports, "__esModule", ({
  989. value: true
  990. }));
  991. exports.SimpleLinkService = exports.PDFLinkService = exports.LinkTarget = void 0;
  992. var _ui_utils = __w_pdfjs_require__(6);
  993. const DEFAULT_LINK_REL = "noopener noreferrer nofollow";
  994. const LinkTarget = {
  995. NONE: 0,
  996. SELF: 1,
  997. BLANK: 2,
  998. PARENT: 3,
  999. TOP: 4
  1000. };
  1001. exports.LinkTarget = LinkTarget;
  1002. function addLinkAttributes(link, {
  1003. url,
  1004. target,
  1005. rel,
  1006. enabled = true
  1007. } = {}) {
  1008. if (!url || typeof url !== "string") {
  1009. throw new Error('A valid "url" parameter must provided.');
  1010. }
  1011. const urlNullRemoved = (0, _ui_utils.removeNullCharacters)(url);
  1012. if (enabled) {
  1013. link.href = link.title = urlNullRemoved;
  1014. } else {
  1015. link.href = "";
  1016. link.title = `Disabled: ${urlNullRemoved}`;
  1017. link.onclick = () => {
  1018. return false;
  1019. };
  1020. }
  1021. let targetStr = "";
  1022. switch (target) {
  1023. case LinkTarget.NONE:
  1024. break;
  1025. case LinkTarget.SELF:
  1026. targetStr = "_self";
  1027. break;
  1028. case LinkTarget.BLANK:
  1029. targetStr = "_blank";
  1030. break;
  1031. case LinkTarget.PARENT:
  1032. targetStr = "_parent";
  1033. break;
  1034. case LinkTarget.TOP:
  1035. targetStr = "_top";
  1036. break;
  1037. }
  1038. link.target = targetStr;
  1039. link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL;
  1040. }
  1041. class PDFLinkService {
  1042. #pagesRefCache = new Map();
  1043. constructor({
  1044. eventBus,
  1045. externalLinkTarget = null,
  1046. externalLinkRel = null,
  1047. ignoreDestinationZoom = false
  1048. } = {}) {
  1049. this.eventBus = eventBus;
  1050. this.externalLinkTarget = externalLinkTarget;
  1051. this.externalLinkRel = externalLinkRel;
  1052. this.externalLinkEnabled = true;
  1053. this._ignoreDestinationZoom = ignoreDestinationZoom;
  1054. this.baseUrl = null;
  1055. this.pdfDocument = null;
  1056. this.pdfViewer = null;
  1057. this.pdfHistory = null;
  1058. }
  1059. setDocument(pdfDocument, baseUrl = null) {
  1060. this.baseUrl = baseUrl;
  1061. this.pdfDocument = pdfDocument;
  1062. this.#pagesRefCache.clear();
  1063. }
  1064. setViewer(pdfViewer) {
  1065. this.pdfViewer = pdfViewer;
  1066. }
  1067. setHistory(pdfHistory) {
  1068. this.pdfHistory = pdfHistory;
  1069. }
  1070. get pagesCount() {
  1071. return this.pdfDocument ? this.pdfDocument.numPages : 0;
  1072. }
  1073. get page() {
  1074. return this.pdfViewer.currentPageNumber;
  1075. }
  1076. set page(value) {
  1077. this.pdfViewer.currentPageNumber = value;
  1078. }
  1079. get rotation() {
  1080. return this.pdfViewer.pagesRotation;
  1081. }
  1082. set rotation(value) {
  1083. this.pdfViewer.pagesRotation = value;
  1084. }
  1085. get isInPresentationMode() {
  1086. return this.pdfViewer.isInPresentationMode;
  1087. }
  1088. #goToDestinationHelper(rawDest, namedDest = null, explicitDest) {
  1089. const destRef = explicitDest[0];
  1090. let pageNumber;
  1091. if (typeof destRef === "object" && destRef !== null) {
  1092. pageNumber = this._cachedPageNumber(destRef);
  1093. if (!pageNumber) {
  1094. this.pdfDocument.getPageIndex(destRef).then(pageIndex => {
  1095. this.cachePageRef(pageIndex + 1, destRef);
  1096. this.#goToDestinationHelper(rawDest, namedDest, explicitDest);
  1097. }).catch(() => {
  1098. console.error(`PDFLinkService.#goToDestinationHelper: "${destRef}" is not ` + `a valid page reference, for dest="${rawDest}".`);
  1099. });
  1100. return;
  1101. }
  1102. } else if (Number.isInteger(destRef)) {
  1103. pageNumber = destRef + 1;
  1104. } else {
  1105. console.error(`PDFLinkService.#goToDestinationHelper: "${destRef}" is not ` + `a valid destination reference, for dest="${rawDest}".`);
  1106. return;
  1107. }
  1108. if (!pageNumber || pageNumber < 1 || pageNumber > this.pagesCount) {
  1109. console.error(`PDFLinkService.#goToDestinationHelper: "${pageNumber}" is not ` + `a valid page number, for dest="${rawDest}".`);
  1110. return;
  1111. }
  1112. if (this.pdfHistory) {
  1113. this.pdfHistory.pushCurrentPosition();
  1114. this.pdfHistory.push({
  1115. namedDest,
  1116. explicitDest,
  1117. pageNumber
  1118. });
  1119. }
  1120. this.pdfViewer.scrollPageIntoView({
  1121. pageNumber,
  1122. destArray: explicitDest,
  1123. ignoreDestinationZoom: this._ignoreDestinationZoom
  1124. });
  1125. }
  1126. async goToDestination(dest) {
  1127. if (!this.pdfDocument) {
  1128. return;
  1129. }
  1130. let namedDest, explicitDest;
  1131. if (typeof dest === "string") {
  1132. namedDest = dest;
  1133. explicitDest = await this.pdfDocument.getDestination(dest);
  1134. } else {
  1135. namedDest = null;
  1136. explicitDest = await dest;
  1137. }
  1138. if (!Array.isArray(explicitDest)) {
  1139. console.error(`PDFLinkService.goToDestination: "${explicitDest}" is not ` + `a valid destination array, for dest="${dest}".`);
  1140. return;
  1141. }
  1142. this.#goToDestinationHelper(dest, namedDest, explicitDest);
  1143. }
  1144. goToPage(val) {
  1145. if (!this.pdfDocument) {
  1146. return;
  1147. }
  1148. const pageNumber = typeof val === "string" && this.pdfViewer.pageLabelToPageNumber(val) || val | 0;
  1149. if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) {
  1150. console.error(`PDFLinkService.goToPage: "${val}" is not a valid page.`);
  1151. return;
  1152. }
  1153. if (this.pdfHistory) {
  1154. this.pdfHistory.pushCurrentPosition();
  1155. this.pdfHistory.pushPage(pageNumber);
  1156. }
  1157. this.pdfViewer.scrollPageIntoView({
  1158. pageNumber
  1159. });
  1160. }
  1161. addLinkAttributes(link, url, newWindow = false) {
  1162. addLinkAttributes(link, {
  1163. url,
  1164. target: newWindow ? LinkTarget.BLANK : this.externalLinkTarget,
  1165. rel: this.externalLinkRel,
  1166. enabled: this.externalLinkEnabled
  1167. });
  1168. }
  1169. getDestinationHash(dest) {
  1170. if (typeof dest === "string") {
  1171. if (dest.length > 0) {
  1172. return this.getAnchorUrl("#" + escape(dest));
  1173. }
  1174. } else if (Array.isArray(dest)) {
  1175. const str = JSON.stringify(dest);
  1176. if (str.length > 0) {
  1177. return this.getAnchorUrl("#" + escape(str));
  1178. }
  1179. }
  1180. return this.getAnchorUrl("");
  1181. }
  1182. getAnchorUrl(anchor) {
  1183. return (this.baseUrl || "") + anchor;
  1184. }
  1185. setHash(hash) {
  1186. if (!this.pdfDocument) {
  1187. return;
  1188. }
  1189. let pageNumber, dest;
  1190. if (hash.includes("=")) {
  1191. const params = (0, _ui_utils.parseQueryString)(hash);
  1192. if (params.has("search")) {
  1193. this.eventBus.dispatch("findfromurlhash", {
  1194. source: this,
  1195. query: params.get("search").replace(/"/g, ""),
  1196. phraseSearch: params.get("phrase") === "true"
  1197. });
  1198. }
  1199. if (params.has("page")) {
  1200. pageNumber = params.get("page") | 0 || 1;
  1201. }
  1202. if (params.has("zoom")) {
  1203. const zoomArgs = params.get("zoom").split(",");
  1204. const zoomArg = zoomArgs[0];
  1205. const zoomArgNumber = parseFloat(zoomArg);
  1206. if (!zoomArg.includes("Fit")) {
  1207. dest = [null, {
  1208. name: "XYZ"
  1209. }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null, zoomArgs.length > 2 ? zoomArgs[2] | 0 : null, zoomArgNumber ? zoomArgNumber / 100 : zoomArg];
  1210. } else {
  1211. if (zoomArg === "Fit" || zoomArg === "FitB") {
  1212. dest = [null, {
  1213. name: zoomArg
  1214. }];
  1215. } else if (zoomArg === "FitH" || zoomArg === "FitBH" || zoomArg === "FitV" || zoomArg === "FitBV") {
  1216. dest = [null, {
  1217. name: zoomArg
  1218. }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null];
  1219. } else if (zoomArg === "FitR") {
  1220. if (zoomArgs.length !== 5) {
  1221. console.error('PDFLinkService.setHash: Not enough parameters for "FitR".');
  1222. } else {
  1223. dest = [null, {
  1224. name: zoomArg
  1225. }, zoomArgs[1] | 0, zoomArgs[2] | 0, zoomArgs[3] | 0, zoomArgs[4] | 0];
  1226. }
  1227. } else {
  1228. console.error(`PDFLinkService.setHash: "${zoomArg}" is not a valid zoom value.`);
  1229. }
  1230. }
  1231. }
  1232. if (dest) {
  1233. this.pdfViewer.scrollPageIntoView({
  1234. pageNumber: pageNumber || this.page,
  1235. destArray: dest,
  1236. allowNegativeOffset: true
  1237. });
  1238. } else if (pageNumber) {
  1239. this.page = pageNumber;
  1240. }
  1241. if (params.has("pagemode")) {
  1242. this.eventBus.dispatch("pagemode", {
  1243. source: this,
  1244. mode: params.get("pagemode")
  1245. });
  1246. }
  1247. if (params.has("nameddest")) {
  1248. this.goToDestination(params.get("nameddest"));
  1249. }
  1250. } else {
  1251. dest = unescape(hash);
  1252. try {
  1253. dest = JSON.parse(dest);
  1254. if (!Array.isArray(dest)) {
  1255. dest = dest.toString();
  1256. }
  1257. } catch (ex) {}
  1258. if (typeof dest === "string" || PDFLinkService.#isValidExplicitDestination(dest)) {
  1259. this.goToDestination(dest);
  1260. return;
  1261. }
  1262. console.error(`PDFLinkService.setHash: "${unescape(hash)}" is not a valid destination.`);
  1263. }
  1264. }
  1265. executeNamedAction(action) {
  1266. switch (action) {
  1267. case "GoBack":
  1268. this.pdfHistory?.back();
  1269. break;
  1270. case "GoForward":
  1271. this.pdfHistory?.forward();
  1272. break;
  1273. case "NextPage":
  1274. this.pdfViewer.nextPage();
  1275. break;
  1276. case "PrevPage":
  1277. this.pdfViewer.previousPage();
  1278. break;
  1279. case "LastPage":
  1280. this.page = this.pagesCount;
  1281. break;
  1282. case "FirstPage":
  1283. this.page = 1;
  1284. break;
  1285. default:
  1286. break;
  1287. }
  1288. this.eventBus.dispatch("namedaction", {
  1289. source: this,
  1290. action
  1291. });
  1292. }
  1293. async executeSetOCGState(action) {
  1294. const pdfDocument = this.pdfDocument;
  1295. const optionalContentConfig = await this.pdfViewer.optionalContentConfigPromise;
  1296. if (pdfDocument !== this.pdfDocument) {
  1297. return;
  1298. }
  1299. let operator;
  1300. for (const elem of action.state) {
  1301. switch (elem) {
  1302. case "ON":
  1303. case "OFF":
  1304. case "Toggle":
  1305. operator = elem;
  1306. continue;
  1307. }
  1308. switch (operator) {
  1309. case "ON":
  1310. optionalContentConfig.setVisibility(elem, true);
  1311. break;
  1312. case "OFF":
  1313. optionalContentConfig.setVisibility(elem, false);
  1314. break;
  1315. case "Toggle":
  1316. const group = optionalContentConfig.getGroup(elem);
  1317. if (group) {
  1318. optionalContentConfig.setVisibility(elem, !group.visible);
  1319. }
  1320. break;
  1321. }
  1322. }
  1323. this.pdfViewer.optionalContentConfigPromise = Promise.resolve(optionalContentConfig);
  1324. }
  1325. cachePageRef(pageNum, pageRef) {
  1326. if (!pageRef) {
  1327. return;
  1328. }
  1329. const refStr = pageRef.gen === 0 ? `${pageRef.num}R` : `${pageRef.num}R${pageRef.gen}`;
  1330. this.#pagesRefCache.set(refStr, pageNum);
  1331. }
  1332. _cachedPageNumber(pageRef) {
  1333. if (!pageRef) {
  1334. return null;
  1335. }
  1336. const refStr = pageRef.gen === 0 ? `${pageRef.num}R` : `${pageRef.num}R${pageRef.gen}`;
  1337. return this.#pagesRefCache.get(refStr) || null;
  1338. }
  1339. isPageVisible(pageNumber) {
  1340. return this.pdfViewer.isPageVisible(pageNumber);
  1341. }
  1342. isPageCached(pageNumber) {
  1343. return this.pdfViewer.isPageCached(pageNumber);
  1344. }
  1345. static #isValidExplicitDestination(dest) {
  1346. if (!Array.isArray(dest)) {
  1347. return false;
  1348. }
  1349. const destLength = dest.length;
  1350. if (destLength < 2) {
  1351. return false;
  1352. }
  1353. const page = dest[0];
  1354. if (!(typeof page === "object" && Number.isInteger(page.num) && Number.isInteger(page.gen)) && !(Number.isInteger(page) && page >= 0)) {
  1355. return false;
  1356. }
  1357. const zoom = dest[1];
  1358. if (!(typeof zoom === "object" && typeof zoom.name === "string")) {
  1359. return false;
  1360. }
  1361. let allowNull = true;
  1362. switch (zoom.name) {
  1363. case "XYZ":
  1364. if (destLength !== 5) {
  1365. return false;
  1366. }
  1367. break;
  1368. case "Fit":
  1369. case "FitB":
  1370. return destLength === 2;
  1371. case "FitH":
  1372. case "FitBH":
  1373. case "FitV":
  1374. case "FitBV":
  1375. if (destLength !== 3) {
  1376. return false;
  1377. }
  1378. break;
  1379. case "FitR":
  1380. if (destLength !== 6) {
  1381. return false;
  1382. }
  1383. allowNull = false;
  1384. break;
  1385. default:
  1386. return false;
  1387. }
  1388. for (let i = 2; i < destLength; i++) {
  1389. const param = dest[i];
  1390. if (!(typeof param === "number" || allowNull && param === null)) {
  1391. return false;
  1392. }
  1393. }
  1394. return true;
  1395. }
  1396. }
  1397. exports.PDFLinkService = PDFLinkService;
  1398. class SimpleLinkService {
  1399. constructor() {
  1400. this.externalLinkEnabled = true;
  1401. }
  1402. get pagesCount() {
  1403. return 0;
  1404. }
  1405. get page() {
  1406. return 0;
  1407. }
  1408. set page(value) {}
  1409. get rotation() {
  1410. return 0;
  1411. }
  1412. set rotation(value) {}
  1413. get isInPresentationMode() {
  1414. return false;
  1415. }
  1416. async goToDestination(dest) {}
  1417. goToPage(val) {}
  1418. addLinkAttributes(link, url, newWindow = false) {
  1419. addLinkAttributes(link, {
  1420. url,
  1421. enabled: this.externalLinkEnabled
  1422. });
  1423. }
  1424. getDestinationHash(dest) {
  1425. return "#";
  1426. }
  1427. getAnchorUrl(hash) {
  1428. return "#";
  1429. }
  1430. setHash(hash) {}
  1431. executeNamedAction(action) {}
  1432. executeSetOCGState(action) {}
  1433. cachePageRef(pageNum, pageRef) {}
  1434. isPageVisible(pageNumber) {
  1435. return true;
  1436. }
  1437. isPageCached(pageNumber) {
  1438. return true;
  1439. }
  1440. }
  1441. exports.SimpleLinkService = SimpleLinkService;
  1442. /***/ }),
  1443. /* 8 */
  1444. /***/ ((__unused_webpack_module, exports) => {
  1445. Object.defineProperty(exports, "__esModule", ({
  1446. value: true
  1447. }));
  1448. exports.StructTreeLayerBuilder = void 0;
  1449. const PDF_ROLE_TO_HTML_ROLE = {
  1450. Document: null,
  1451. DocumentFragment: null,
  1452. Part: "group",
  1453. Sect: "group",
  1454. Div: "group",
  1455. Aside: "note",
  1456. NonStruct: "none",
  1457. P: null,
  1458. H: "heading",
  1459. Title: null,
  1460. FENote: "note",
  1461. Sub: "group",
  1462. Lbl: null,
  1463. Span: null,
  1464. Em: null,
  1465. Strong: null,
  1466. Link: "link",
  1467. Annot: "note",
  1468. Form: "form",
  1469. Ruby: null,
  1470. RB: null,
  1471. RT: null,
  1472. RP: null,
  1473. Warichu: null,
  1474. WT: null,
  1475. WP: null,
  1476. L: "list",
  1477. LI: "listitem",
  1478. LBody: null,
  1479. Table: "table",
  1480. TR: "row",
  1481. TH: "columnheader",
  1482. TD: "cell",
  1483. THead: "columnheader",
  1484. TBody: null,
  1485. TFoot: null,
  1486. Caption: null,
  1487. Figure: "figure",
  1488. Formula: null,
  1489. Artifact: null
  1490. };
  1491. const HEADING_PATTERN = /^H(\d+)$/;
  1492. class StructTreeLayerBuilder {
  1493. constructor({
  1494. pdfPage
  1495. }) {
  1496. this.pdfPage = pdfPage;
  1497. }
  1498. render(structTree) {
  1499. return this._walk(structTree);
  1500. }
  1501. _setAttributes(structElement, htmlElement) {
  1502. if (structElement.alt !== undefined) {
  1503. htmlElement.setAttribute("aria-label", structElement.alt);
  1504. }
  1505. if (structElement.id !== undefined) {
  1506. htmlElement.setAttribute("aria-owns", structElement.id);
  1507. }
  1508. if (structElement.lang !== undefined) {
  1509. htmlElement.setAttribute("lang", structElement.lang);
  1510. }
  1511. }
  1512. _walk(node) {
  1513. if (!node) {
  1514. return null;
  1515. }
  1516. const element = document.createElement("span");
  1517. if ("role" in node) {
  1518. const {
  1519. role
  1520. } = node;
  1521. const match = role.match(HEADING_PATTERN);
  1522. if (match) {
  1523. element.setAttribute("role", "heading");
  1524. element.setAttribute("aria-level", match[1]);
  1525. } else if (PDF_ROLE_TO_HTML_ROLE[role]) {
  1526. element.setAttribute("role", PDF_ROLE_TO_HTML_ROLE[role]);
  1527. }
  1528. }
  1529. this._setAttributes(node, element);
  1530. if (node.children) {
  1531. if (node.children.length === 1 && "id" in node.children[0]) {
  1532. this._setAttributes(node.children[0], element);
  1533. } else {
  1534. for (const kid of node.children) {
  1535. element.append(this._walk(kid));
  1536. }
  1537. }
  1538. }
  1539. return element;
  1540. }
  1541. }
  1542. exports.StructTreeLayerBuilder = StructTreeLayerBuilder;
  1543. /***/ }),
  1544. /* 9 */
  1545. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  1546. Object.defineProperty(exports, "__esModule", ({
  1547. value: true
  1548. }));
  1549. exports.TextLayerBuilder = void 0;
  1550. var _pdfjsLib = __w_pdfjs_require__(3);
  1551. class TextLayerBuilder {
  1552. constructor({
  1553. textLayerDiv,
  1554. eventBus,
  1555. pageIndex,
  1556. viewport,
  1557. highlighter = null,
  1558. accessibilityManager = null
  1559. }) {
  1560. this.textLayerDiv = textLayerDiv;
  1561. this.eventBus = eventBus;
  1562. this.textContent = null;
  1563. this.textContentItemsStr = [];
  1564. this.textContentStream = null;
  1565. this.renderingDone = false;
  1566. this.pageNumber = pageIndex + 1;
  1567. this.viewport = viewport;
  1568. this.textDivs = [];
  1569. this.textLayerRenderTask = null;
  1570. this.highlighter = highlighter;
  1571. this.accessibilityManager = accessibilityManager;
  1572. this.#bindMouse();
  1573. }
  1574. #finishRendering() {
  1575. this.renderingDone = true;
  1576. const endOfContent = document.createElement("div");
  1577. endOfContent.className = "endOfContent";
  1578. this.textLayerDiv.append(endOfContent);
  1579. this.eventBus.dispatch("textlayerrendered", {
  1580. source: this,
  1581. pageNumber: this.pageNumber,
  1582. numTextDivs: this.textDivs.length
  1583. });
  1584. }
  1585. render(timeout = 0) {
  1586. if (!(this.textContent || this.textContentStream) || this.renderingDone) {
  1587. return;
  1588. }
  1589. this.cancel();
  1590. this.textDivs.length = 0;
  1591. this.highlighter?.setTextMapping(this.textDivs, this.textContentItemsStr);
  1592. this.accessibilityManager?.setTextMapping(this.textDivs);
  1593. const textLayerFrag = document.createDocumentFragment();
  1594. this.textLayerRenderTask = (0, _pdfjsLib.renderTextLayer)({
  1595. textContent: this.textContent,
  1596. textContentStream: this.textContentStream,
  1597. container: textLayerFrag,
  1598. viewport: this.viewport,
  1599. textDivs: this.textDivs,
  1600. textContentItemsStr: this.textContentItemsStr,
  1601. timeout
  1602. });
  1603. this.textLayerRenderTask.promise.then(() => {
  1604. this.textLayerDiv.append(textLayerFrag);
  1605. this.#finishRendering();
  1606. this.highlighter?.enable();
  1607. this.accessibilityManager?.enable();
  1608. }, function (reason) {});
  1609. }
  1610. cancel() {
  1611. if (this.textLayerRenderTask) {
  1612. this.textLayerRenderTask.cancel();
  1613. this.textLayerRenderTask = null;
  1614. }
  1615. this.highlighter?.disable();
  1616. this.accessibilityManager?.disable();
  1617. }
  1618. setTextContentStream(readableStream) {
  1619. this.cancel();
  1620. this.textContentStream = readableStream;
  1621. }
  1622. setTextContent(textContent) {
  1623. this.cancel();
  1624. this.textContent = textContent;
  1625. }
  1626. #bindMouse() {
  1627. const div = this.textLayerDiv;
  1628. div.addEventListener("mousedown", evt => {
  1629. const end = div.querySelector(".endOfContent");
  1630. if (!end) {
  1631. return;
  1632. }
  1633. let adjustTop = evt.target !== div;
  1634. adjustTop &&= getComputedStyle(end).getPropertyValue("-moz-user-select") !== "none";
  1635. if (adjustTop) {
  1636. const divBounds = div.getBoundingClientRect();
  1637. const r = Math.max(0, (evt.pageY - divBounds.top) / divBounds.height);
  1638. end.style.top = (r * 100).toFixed(2) + "%";
  1639. }
  1640. end.classList.add("active");
  1641. });
  1642. div.addEventListener("mouseup", () => {
  1643. const end = div.querySelector(".endOfContent");
  1644. if (!end) {
  1645. return;
  1646. }
  1647. end.style.top = "";
  1648. end.classList.remove("active");
  1649. });
  1650. }
  1651. }
  1652. exports.TextLayerBuilder = TextLayerBuilder;
  1653. /***/ }),
  1654. /* 10 */
  1655. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  1656. Object.defineProperty(exports, "__esModule", ({
  1657. value: true
  1658. }));
  1659. exports.XfaLayerBuilder = void 0;
  1660. var _pdfjsLib = __w_pdfjs_require__(3);
  1661. class XfaLayerBuilder {
  1662. constructor({
  1663. pageDiv,
  1664. pdfPage,
  1665. annotationStorage = null,
  1666. linkService,
  1667. xfaHtml = null
  1668. }) {
  1669. this.pageDiv = pageDiv;
  1670. this.pdfPage = pdfPage;
  1671. this.annotationStorage = annotationStorage;
  1672. this.linkService = linkService;
  1673. this.xfaHtml = xfaHtml;
  1674. this.div = null;
  1675. this._cancelled = false;
  1676. }
  1677. render(viewport, intent = "display") {
  1678. if (intent === "print") {
  1679. const parameters = {
  1680. viewport: viewport.clone({
  1681. dontFlip: true
  1682. }),
  1683. div: this.div,
  1684. xfaHtml: this.xfaHtml,
  1685. annotationStorage: this.annotationStorage,
  1686. linkService: this.linkService,
  1687. intent
  1688. };
  1689. const div = document.createElement("div");
  1690. this.pageDiv.append(div);
  1691. parameters.div = div;
  1692. const result = _pdfjsLib.XfaLayer.render(parameters);
  1693. return Promise.resolve(result);
  1694. }
  1695. return this.pdfPage.getXfa().then(xfaHtml => {
  1696. if (this._cancelled || !xfaHtml) {
  1697. return {
  1698. textDivs: []
  1699. };
  1700. }
  1701. const parameters = {
  1702. viewport: viewport.clone({
  1703. dontFlip: true
  1704. }),
  1705. div: this.div,
  1706. xfaHtml,
  1707. annotationStorage: this.annotationStorage,
  1708. linkService: this.linkService,
  1709. intent
  1710. };
  1711. if (this.div) {
  1712. return _pdfjsLib.XfaLayer.update(parameters);
  1713. }
  1714. this.div = document.createElement("div");
  1715. this.pageDiv.append(this.div);
  1716. parameters.div = this.div;
  1717. return _pdfjsLib.XfaLayer.render(parameters);
  1718. }).catch(error => {
  1719. console.error(error);
  1720. });
  1721. }
  1722. cancel() {
  1723. this._cancelled = true;
  1724. }
  1725. hide() {
  1726. if (!this.div) {
  1727. return;
  1728. }
  1729. this.div.hidden = true;
  1730. }
  1731. }
  1732. exports.XfaLayerBuilder = XfaLayerBuilder;
  1733. /***/ }),
  1734. /* 11 */
  1735. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  1736. Object.defineProperty(exports, "__esModule", ({
  1737. value: true
  1738. }));
  1739. exports.DownloadManager = void 0;
  1740. var _pdfjsLib = __w_pdfjs_require__(3);
  1741. ;
  1742. function download(blobUrl, filename) {
  1743. const a = document.createElement("a");
  1744. if (!a.click) {
  1745. throw new Error('DownloadManager: "a.click()" is not supported.');
  1746. }
  1747. a.href = blobUrl;
  1748. a.target = "_parent";
  1749. if ("download" in a) {
  1750. a.download = filename;
  1751. }
  1752. (document.body || document.documentElement).append(a);
  1753. a.click();
  1754. a.remove();
  1755. }
  1756. class DownloadManager {
  1757. #openBlobUrls = new WeakMap();
  1758. downloadUrl(url, filename) {
  1759. if (!(0, _pdfjsLib.createValidAbsoluteUrl)(url, "http://example.com")) {
  1760. console.error(`downloadUrl - not a valid URL: ${url}`);
  1761. return;
  1762. }
  1763. download(url + "#pdfjs.action=download", filename);
  1764. }
  1765. downloadData(data, filename, contentType) {
  1766. const blobUrl = URL.createObjectURL(new Blob([data], {
  1767. type: contentType
  1768. }));
  1769. download(blobUrl, filename);
  1770. }
  1771. openOrDownloadData(element, data, filename) {
  1772. const isPdfData = (0, _pdfjsLib.isPdfFile)(filename);
  1773. const contentType = isPdfData ? "application/pdf" : "";
  1774. if (isPdfData) {
  1775. let blobUrl = this.#openBlobUrls.get(element);
  1776. if (!blobUrl) {
  1777. blobUrl = URL.createObjectURL(new Blob([data], {
  1778. type: contentType
  1779. }));
  1780. this.#openBlobUrls.set(element, blobUrl);
  1781. }
  1782. let viewerUrl;
  1783. viewerUrl = "?file=" + encodeURIComponent(blobUrl + "#" + filename);
  1784. try {
  1785. window.open(viewerUrl);
  1786. return true;
  1787. } catch (ex) {
  1788. console.error(`openOrDownloadData: ${ex}`);
  1789. URL.revokeObjectURL(blobUrl);
  1790. this.#openBlobUrls.delete(element);
  1791. }
  1792. }
  1793. this.downloadData(data, filename, contentType);
  1794. return false;
  1795. }
  1796. download(blob, url, filename) {
  1797. const blobUrl = URL.createObjectURL(blob);
  1798. download(blobUrl, filename);
  1799. }
  1800. }
  1801. exports.DownloadManager = DownloadManager;
  1802. /***/ }),
  1803. /* 12 */
  1804. /***/ ((__unused_webpack_module, exports) => {
  1805. Object.defineProperty(exports, "__esModule", ({
  1806. value: true
  1807. }));
  1808. exports.WaitOnType = exports.EventBus = exports.AutomationEventBus = void 0;
  1809. exports.waitOnEventOrTimeout = waitOnEventOrTimeout;
  1810. const WaitOnType = {
  1811. EVENT: "event",
  1812. TIMEOUT: "timeout"
  1813. };
  1814. exports.WaitOnType = WaitOnType;
  1815. function waitOnEventOrTimeout({
  1816. target,
  1817. name,
  1818. delay = 0
  1819. }) {
  1820. return new Promise(function (resolve, reject) {
  1821. if (typeof target !== "object" || !(name && typeof name === "string") || !(Number.isInteger(delay) && delay >= 0)) {
  1822. throw new Error("waitOnEventOrTimeout - invalid parameters.");
  1823. }
  1824. function handler(type) {
  1825. if (target instanceof EventBus) {
  1826. target._off(name, eventHandler);
  1827. } else {
  1828. target.removeEventListener(name, eventHandler);
  1829. }
  1830. if (timeout) {
  1831. clearTimeout(timeout);
  1832. }
  1833. resolve(type);
  1834. }
  1835. const eventHandler = handler.bind(null, WaitOnType.EVENT);
  1836. if (target instanceof EventBus) {
  1837. target._on(name, eventHandler);
  1838. } else {
  1839. target.addEventListener(name, eventHandler);
  1840. }
  1841. const timeoutHandler = handler.bind(null, WaitOnType.TIMEOUT);
  1842. const timeout = setTimeout(timeoutHandler, delay);
  1843. });
  1844. }
  1845. class EventBus {
  1846. #listeners = Object.create(null);
  1847. on(eventName, listener, options = null) {
  1848. this._on(eventName, listener, {
  1849. external: true,
  1850. once: options?.once
  1851. });
  1852. }
  1853. off(eventName, listener, options = null) {
  1854. this._off(eventName, listener, {
  1855. external: true,
  1856. once: options?.once
  1857. });
  1858. }
  1859. dispatch(eventName, data) {
  1860. const eventListeners = this.#listeners[eventName];
  1861. if (!eventListeners || eventListeners.length === 0) {
  1862. return;
  1863. }
  1864. let externalListeners;
  1865. for (const {
  1866. listener,
  1867. external,
  1868. once
  1869. } of eventListeners.slice(0)) {
  1870. if (once) {
  1871. this._off(eventName, listener);
  1872. }
  1873. if (external) {
  1874. (externalListeners ||= []).push(listener);
  1875. continue;
  1876. }
  1877. listener(data);
  1878. }
  1879. if (externalListeners) {
  1880. for (const listener of externalListeners) {
  1881. listener(data);
  1882. }
  1883. externalListeners = null;
  1884. }
  1885. }
  1886. _on(eventName, listener, options = null) {
  1887. const eventListeners = this.#listeners[eventName] ||= [];
  1888. eventListeners.push({
  1889. listener,
  1890. external: options?.external === true,
  1891. once: options?.once === true
  1892. });
  1893. }
  1894. _off(eventName, listener, options = null) {
  1895. const eventListeners = this.#listeners[eventName];
  1896. if (!eventListeners) {
  1897. return;
  1898. }
  1899. for (let i = 0, ii = eventListeners.length; i < ii; i++) {
  1900. if (eventListeners[i].listener === listener) {
  1901. eventListeners.splice(i, 1);
  1902. return;
  1903. }
  1904. }
  1905. }
  1906. }
  1907. exports.EventBus = EventBus;
  1908. class AutomationEventBus extends EventBus {
  1909. dispatch(eventName, data) {
  1910. throw new Error("Not implemented: AutomationEventBus.dispatch");
  1911. }
  1912. }
  1913. exports.AutomationEventBus = AutomationEventBus;
  1914. /***/ }),
  1915. /* 13 */
  1916. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  1917. Object.defineProperty(exports, "__esModule", ({
  1918. value: true
  1919. }));
  1920. exports.GenericL10n = void 0;
  1921. __w_pdfjs_require__(14);
  1922. var _l10n_utils = __w_pdfjs_require__(4);
  1923. const webL10n = document.webL10n;
  1924. class GenericL10n {
  1925. constructor(lang) {
  1926. this._lang = lang;
  1927. this._ready = new Promise((resolve, reject) => {
  1928. webL10n.setLanguage((0, _l10n_utils.fixupLangCode)(lang), () => {
  1929. resolve(webL10n);
  1930. });
  1931. });
  1932. }
  1933. async getLanguage() {
  1934. const l10n = await this._ready;
  1935. return l10n.getLanguage();
  1936. }
  1937. async getDirection() {
  1938. const l10n = await this._ready;
  1939. return l10n.getDirection();
  1940. }
  1941. async get(key, args = null, fallback = (0, _l10n_utils.getL10nFallback)(key, args)) {
  1942. const l10n = await this._ready;
  1943. return l10n.get(key, args, fallback);
  1944. }
  1945. async translate(element) {
  1946. const l10n = await this._ready;
  1947. return l10n.translate(element);
  1948. }
  1949. }
  1950. exports.GenericL10n = GenericL10n;
  1951. /***/ }),
  1952. /* 14 */
  1953. /***/ (() => {
  1954. document.webL10n = function (window, document, undefined) {
  1955. var gL10nData = {};
  1956. var gTextData = '';
  1957. var gTextProp = 'textContent';
  1958. var gLanguage = '';
  1959. var gMacros = {};
  1960. var gReadyState = 'loading';
  1961. var gAsyncResourceLoading = true;
  1962. function getL10nResourceLinks() {
  1963. return document.querySelectorAll('link[type="application/l10n"]');
  1964. }
  1965. function getL10nDictionary() {
  1966. var script = document.querySelector('script[type="application/l10n"]');
  1967. return script ? JSON.parse(script.innerHTML) : null;
  1968. }
  1969. function getTranslatableChildren(element) {
  1970. return element ? element.querySelectorAll('*[data-l10n-id]') : [];
  1971. }
  1972. function getL10nAttributes(element) {
  1973. if (!element) return {};
  1974. var l10nId = element.getAttribute('data-l10n-id');
  1975. var l10nArgs = element.getAttribute('data-l10n-args');
  1976. var args = {};
  1977. if (l10nArgs) {
  1978. try {
  1979. args = JSON.parse(l10nArgs);
  1980. } catch (e) {
  1981. console.warn('could not parse arguments for #' + l10nId);
  1982. }
  1983. }
  1984. return {
  1985. id: l10nId,
  1986. args: args
  1987. };
  1988. }
  1989. function xhrLoadText(url, onSuccess, onFailure) {
  1990. onSuccess = onSuccess || function _onSuccess(data) {};
  1991. onFailure = onFailure || function _onFailure() {};
  1992. var xhr = new XMLHttpRequest();
  1993. xhr.open('GET', url, gAsyncResourceLoading);
  1994. if (xhr.overrideMimeType) {
  1995. xhr.overrideMimeType('text/plain; charset=utf-8');
  1996. }
  1997. xhr.onreadystatechange = function () {
  1998. if (xhr.readyState == 4) {
  1999. if (xhr.status == 200 || xhr.status === 0) {
  2000. onSuccess(xhr.responseText);
  2001. } else {
  2002. onFailure();
  2003. }
  2004. }
  2005. };
  2006. xhr.onerror = onFailure;
  2007. xhr.ontimeout = onFailure;
  2008. try {
  2009. xhr.send(null);
  2010. } catch (e) {
  2011. onFailure();
  2012. }
  2013. }
  2014. function parseResource(href, lang, successCallback, failureCallback) {
  2015. var baseURL = href.replace(/[^\/]*$/, '') || './';
  2016. function evalString(text) {
  2017. if (text.lastIndexOf('\\') < 0) return text;
  2018. return text.replace(/\\\\/g, '\\').replace(/\\n/g, '\n').replace(/\\r/g, '\r').replace(/\\t/g, '\t').replace(/\\b/g, '\b').replace(/\\f/g, '\f').replace(/\\{/g, '{').replace(/\\}/g, '}').replace(/\\"/g, '"').replace(/\\'/g, "'");
  2019. }
  2020. function parseProperties(text, parsedPropertiesCallback) {
  2021. var dictionary = {};
  2022. var reBlank = /^\s*|\s*$/;
  2023. var reComment = /^\s*#|^\s*$/;
  2024. var reSection = /^\s*\[(.*)\]\s*$/;
  2025. var reImport = /^\s*@import\s+url\((.*)\)\s*$/i;
  2026. var reSplit = /^([^=\s]*)\s*=\s*(.+)$/;
  2027. function parseRawLines(rawText, extendedSyntax, parsedRawLinesCallback) {
  2028. var entries = rawText.replace(reBlank, '').split(/[\r\n]+/);
  2029. var currentLang = '*';
  2030. var genericLang = lang.split('-', 1)[0];
  2031. var skipLang = false;
  2032. var match = '';
  2033. function nextEntry() {
  2034. while (true) {
  2035. if (!entries.length) {
  2036. parsedRawLinesCallback();
  2037. return;
  2038. }
  2039. var line = entries.shift();
  2040. if (reComment.test(line)) continue;
  2041. if (extendedSyntax) {
  2042. match = reSection.exec(line);
  2043. if (match) {
  2044. currentLang = match[1].toLowerCase();
  2045. skipLang = currentLang !== '*' && currentLang !== lang && currentLang !== genericLang;
  2046. continue;
  2047. } else if (skipLang) {
  2048. continue;
  2049. }
  2050. match = reImport.exec(line);
  2051. if (match) {
  2052. loadImport(baseURL + match[1], nextEntry);
  2053. return;
  2054. }
  2055. }
  2056. var tmp = line.match(reSplit);
  2057. if (tmp && tmp.length == 3) {
  2058. dictionary[tmp[1]] = evalString(tmp[2]);
  2059. }
  2060. }
  2061. }
  2062. nextEntry();
  2063. }
  2064. function loadImport(url, callback) {
  2065. xhrLoadText(url, function (content) {
  2066. parseRawLines(content, false, callback);
  2067. }, function () {
  2068. console.warn(url + ' not found.');
  2069. callback();
  2070. });
  2071. }
  2072. parseRawLines(text, true, function () {
  2073. parsedPropertiesCallback(dictionary);
  2074. });
  2075. }
  2076. xhrLoadText(href, function (response) {
  2077. gTextData += response;
  2078. parseProperties(response, function (data) {
  2079. for (var key in data) {
  2080. var id,
  2081. prop,
  2082. index = key.lastIndexOf('.');
  2083. if (index > 0) {
  2084. id = key.substring(0, index);
  2085. prop = key.substring(index + 1);
  2086. } else {
  2087. id = key;
  2088. prop = gTextProp;
  2089. }
  2090. if (!gL10nData[id]) {
  2091. gL10nData[id] = {};
  2092. }
  2093. gL10nData[id][prop] = data[key];
  2094. }
  2095. if (successCallback) {
  2096. successCallback();
  2097. }
  2098. });
  2099. }, failureCallback);
  2100. }
  2101. function loadLocale(lang, callback) {
  2102. if (lang) {
  2103. lang = lang.toLowerCase();
  2104. }
  2105. callback = callback || function _callback() {};
  2106. clear();
  2107. gLanguage = lang;
  2108. var langLinks = getL10nResourceLinks();
  2109. var langCount = langLinks.length;
  2110. if (langCount === 0) {
  2111. var dict = getL10nDictionary();
  2112. if (dict && dict.locales && dict.default_locale) {
  2113. console.log('using the embedded JSON directory, early way out');
  2114. gL10nData = dict.locales[lang];
  2115. if (!gL10nData) {
  2116. var defaultLocale = dict.default_locale.toLowerCase();
  2117. for (var anyCaseLang in dict.locales) {
  2118. anyCaseLang = anyCaseLang.toLowerCase();
  2119. if (anyCaseLang === lang) {
  2120. gL10nData = dict.locales[lang];
  2121. break;
  2122. } else if (anyCaseLang === defaultLocale) {
  2123. gL10nData = dict.locales[defaultLocale];
  2124. }
  2125. }
  2126. }
  2127. callback();
  2128. } else {
  2129. console.log('no resource to load, early way out');
  2130. }
  2131. gReadyState = 'complete';
  2132. return;
  2133. }
  2134. var onResourceLoaded = null;
  2135. var gResourceCount = 0;
  2136. onResourceLoaded = function () {
  2137. gResourceCount++;
  2138. if (gResourceCount >= langCount) {
  2139. callback();
  2140. gReadyState = 'complete';
  2141. }
  2142. };
  2143. function L10nResourceLink(link) {
  2144. var href = link.href;
  2145. this.load = function (lang, callback) {
  2146. parseResource(href, lang, callback, function () {
  2147. console.warn(href + ' not found.');
  2148. console.warn('"' + lang + '" resource not found');
  2149. gLanguage = '';
  2150. callback();
  2151. });
  2152. };
  2153. }
  2154. for (var i = 0; i < langCount; i++) {
  2155. var resource = new L10nResourceLink(langLinks[i]);
  2156. resource.load(lang, onResourceLoaded);
  2157. }
  2158. }
  2159. function clear() {
  2160. gL10nData = {};
  2161. gTextData = '';
  2162. gLanguage = '';
  2163. }
  2164. function getPluralRules(lang) {
  2165. var locales2rules = {
  2166. 'af': 3,
  2167. 'ak': 4,
  2168. 'am': 4,
  2169. 'ar': 1,
  2170. 'asa': 3,
  2171. 'az': 0,
  2172. 'be': 11,
  2173. 'bem': 3,
  2174. 'bez': 3,
  2175. 'bg': 3,
  2176. 'bh': 4,
  2177. 'bm': 0,
  2178. 'bn': 3,
  2179. 'bo': 0,
  2180. 'br': 20,
  2181. 'brx': 3,
  2182. 'bs': 11,
  2183. 'ca': 3,
  2184. 'cgg': 3,
  2185. 'chr': 3,
  2186. 'cs': 12,
  2187. 'cy': 17,
  2188. 'da': 3,
  2189. 'de': 3,
  2190. 'dv': 3,
  2191. 'dz': 0,
  2192. 'ee': 3,
  2193. 'el': 3,
  2194. 'en': 3,
  2195. 'eo': 3,
  2196. 'es': 3,
  2197. 'et': 3,
  2198. 'eu': 3,
  2199. 'fa': 0,
  2200. 'ff': 5,
  2201. 'fi': 3,
  2202. 'fil': 4,
  2203. 'fo': 3,
  2204. 'fr': 5,
  2205. 'fur': 3,
  2206. 'fy': 3,
  2207. 'ga': 8,
  2208. 'gd': 24,
  2209. 'gl': 3,
  2210. 'gsw': 3,
  2211. 'gu': 3,
  2212. 'guw': 4,
  2213. 'gv': 23,
  2214. 'ha': 3,
  2215. 'haw': 3,
  2216. 'he': 2,
  2217. 'hi': 4,
  2218. 'hr': 11,
  2219. 'hu': 0,
  2220. 'id': 0,
  2221. 'ig': 0,
  2222. 'ii': 0,
  2223. 'is': 3,
  2224. 'it': 3,
  2225. 'iu': 7,
  2226. 'ja': 0,
  2227. 'jmc': 3,
  2228. 'jv': 0,
  2229. 'ka': 0,
  2230. 'kab': 5,
  2231. 'kaj': 3,
  2232. 'kcg': 3,
  2233. 'kde': 0,
  2234. 'kea': 0,
  2235. 'kk': 3,
  2236. 'kl': 3,
  2237. 'km': 0,
  2238. 'kn': 0,
  2239. 'ko': 0,
  2240. 'ksb': 3,
  2241. 'ksh': 21,
  2242. 'ku': 3,
  2243. 'kw': 7,
  2244. 'lag': 18,
  2245. 'lb': 3,
  2246. 'lg': 3,
  2247. 'ln': 4,
  2248. 'lo': 0,
  2249. 'lt': 10,
  2250. 'lv': 6,
  2251. 'mas': 3,
  2252. 'mg': 4,
  2253. 'mk': 16,
  2254. 'ml': 3,
  2255. 'mn': 3,
  2256. 'mo': 9,
  2257. 'mr': 3,
  2258. 'ms': 0,
  2259. 'mt': 15,
  2260. 'my': 0,
  2261. 'nah': 3,
  2262. 'naq': 7,
  2263. 'nb': 3,
  2264. 'nd': 3,
  2265. 'ne': 3,
  2266. 'nl': 3,
  2267. 'nn': 3,
  2268. 'no': 3,
  2269. 'nr': 3,
  2270. 'nso': 4,
  2271. 'ny': 3,
  2272. 'nyn': 3,
  2273. 'om': 3,
  2274. 'or': 3,
  2275. 'pa': 3,
  2276. 'pap': 3,
  2277. 'pl': 13,
  2278. 'ps': 3,
  2279. 'pt': 3,
  2280. 'rm': 3,
  2281. 'ro': 9,
  2282. 'rof': 3,
  2283. 'ru': 11,
  2284. 'rwk': 3,
  2285. 'sah': 0,
  2286. 'saq': 3,
  2287. 'se': 7,
  2288. 'seh': 3,
  2289. 'ses': 0,
  2290. 'sg': 0,
  2291. 'sh': 11,
  2292. 'shi': 19,
  2293. 'sk': 12,
  2294. 'sl': 14,
  2295. 'sma': 7,
  2296. 'smi': 7,
  2297. 'smj': 7,
  2298. 'smn': 7,
  2299. 'sms': 7,
  2300. 'sn': 3,
  2301. 'so': 3,
  2302. 'sq': 3,
  2303. 'sr': 11,
  2304. 'ss': 3,
  2305. 'ssy': 3,
  2306. 'st': 3,
  2307. 'sv': 3,
  2308. 'sw': 3,
  2309. 'syr': 3,
  2310. 'ta': 3,
  2311. 'te': 3,
  2312. 'teo': 3,
  2313. 'th': 0,
  2314. 'ti': 4,
  2315. 'tig': 3,
  2316. 'tk': 3,
  2317. 'tl': 4,
  2318. 'tn': 3,
  2319. 'to': 0,
  2320. 'tr': 0,
  2321. 'ts': 3,
  2322. 'tzm': 22,
  2323. 'uk': 11,
  2324. 'ur': 3,
  2325. 've': 3,
  2326. 'vi': 0,
  2327. 'vun': 3,
  2328. 'wa': 4,
  2329. 'wae': 3,
  2330. 'wo': 0,
  2331. 'xh': 3,
  2332. 'xog': 3,
  2333. 'yo': 0,
  2334. 'zh': 0,
  2335. 'zu': 3
  2336. };
  2337. function isIn(n, list) {
  2338. return list.indexOf(n) !== -1;
  2339. }
  2340. function isBetween(n, start, end) {
  2341. return start <= n && n <= end;
  2342. }
  2343. var pluralRules = {
  2344. '0': function (n) {
  2345. return 'other';
  2346. },
  2347. '1': function (n) {
  2348. if (isBetween(n % 100, 3, 10)) return 'few';
  2349. if (n === 0) return 'zero';
  2350. if (isBetween(n % 100, 11, 99)) return 'many';
  2351. if (n == 2) return 'two';
  2352. if (n == 1) return 'one';
  2353. return 'other';
  2354. },
  2355. '2': function (n) {
  2356. if (n !== 0 && n % 10 === 0) return 'many';
  2357. if (n == 2) return 'two';
  2358. if (n == 1) return 'one';
  2359. return 'other';
  2360. },
  2361. '3': function (n) {
  2362. if (n == 1) return 'one';
  2363. return 'other';
  2364. },
  2365. '4': function (n) {
  2366. if (isBetween(n, 0, 1)) return 'one';
  2367. return 'other';
  2368. },
  2369. '5': function (n) {
  2370. if (isBetween(n, 0, 2) && n != 2) return 'one';
  2371. return 'other';
  2372. },
  2373. '6': function (n) {
  2374. if (n === 0) return 'zero';
  2375. if (n % 10 == 1 && n % 100 != 11) return 'one';
  2376. return 'other';
  2377. },
  2378. '7': function (n) {
  2379. if (n == 2) return 'two';
  2380. if (n == 1) return 'one';
  2381. return 'other';
  2382. },
  2383. '8': function (n) {
  2384. if (isBetween(n, 3, 6)) return 'few';
  2385. if (isBetween(n, 7, 10)) return 'many';
  2386. if (n == 2) return 'two';
  2387. if (n == 1) return 'one';
  2388. return 'other';
  2389. },
  2390. '9': function (n) {
  2391. if (n === 0 || n != 1 && isBetween(n % 100, 1, 19)) return 'few';
  2392. if (n == 1) return 'one';
  2393. return 'other';
  2394. },
  2395. '10': function (n) {
  2396. if (isBetween(n % 10, 2, 9) && !isBetween(n % 100, 11, 19)) return 'few';
  2397. if (n % 10 == 1 && !isBetween(n % 100, 11, 19)) return 'one';
  2398. return 'other';
  2399. },
  2400. '11': function (n) {
  2401. if (isBetween(n % 10, 2, 4) && !isBetween(n % 100, 12, 14)) return 'few';
  2402. if (n % 10 === 0 || isBetween(n % 10, 5, 9) || isBetween(n % 100, 11, 14)) return 'many';
  2403. if (n % 10 == 1 && n % 100 != 11) return 'one';
  2404. return 'other';
  2405. },
  2406. '12': function (n) {
  2407. if (isBetween(n, 2, 4)) return 'few';
  2408. if (n == 1) return 'one';
  2409. return 'other';
  2410. },
  2411. '13': function (n) {
  2412. if (isBetween(n % 10, 2, 4) && !isBetween(n % 100, 12, 14)) return 'few';
  2413. if (n != 1 && isBetween(n % 10, 0, 1) || isBetween(n % 10, 5, 9) || isBetween(n % 100, 12, 14)) return 'many';
  2414. if (n == 1) return 'one';
  2415. return 'other';
  2416. },
  2417. '14': function (n) {
  2418. if (isBetween(n % 100, 3, 4)) return 'few';
  2419. if (n % 100 == 2) return 'two';
  2420. if (n % 100 == 1) return 'one';
  2421. return 'other';
  2422. },
  2423. '15': function (n) {
  2424. if (n === 0 || isBetween(n % 100, 2, 10)) return 'few';
  2425. if (isBetween(n % 100, 11, 19)) return 'many';
  2426. if (n == 1) return 'one';
  2427. return 'other';
  2428. },
  2429. '16': function (n) {
  2430. if (n % 10 == 1 && n != 11) return 'one';
  2431. return 'other';
  2432. },
  2433. '17': function (n) {
  2434. if (n == 3) return 'few';
  2435. if (n === 0) return 'zero';
  2436. if (n == 6) return 'many';
  2437. if (n == 2) return 'two';
  2438. if (n == 1) return 'one';
  2439. return 'other';
  2440. },
  2441. '18': function (n) {
  2442. if (n === 0) return 'zero';
  2443. if (isBetween(n, 0, 2) && n !== 0 && n != 2) return 'one';
  2444. return 'other';
  2445. },
  2446. '19': function (n) {
  2447. if (isBetween(n, 2, 10)) return 'few';
  2448. if (isBetween(n, 0, 1)) return 'one';
  2449. return 'other';
  2450. },
  2451. '20': function (n) {
  2452. if ((isBetween(n % 10, 3, 4) || n % 10 == 9) && !(isBetween(n % 100, 10, 19) || isBetween(n % 100, 70, 79) || isBetween(n % 100, 90, 99))) return 'few';
  2453. if (n % 1000000 === 0 && n !== 0) return 'many';
  2454. if (n % 10 == 2 && !isIn(n % 100, [12, 72, 92])) return 'two';
  2455. if (n % 10 == 1 && !isIn(n % 100, [11, 71, 91])) return 'one';
  2456. return 'other';
  2457. },
  2458. '21': function (n) {
  2459. if (n === 0) return 'zero';
  2460. if (n == 1) return 'one';
  2461. return 'other';
  2462. },
  2463. '22': function (n) {
  2464. if (isBetween(n, 0, 1) || isBetween(n, 11, 99)) return 'one';
  2465. return 'other';
  2466. },
  2467. '23': function (n) {
  2468. if (isBetween(n % 10, 1, 2) || n % 20 === 0) return 'one';
  2469. return 'other';
  2470. },
  2471. '24': function (n) {
  2472. if (isBetween(n, 3, 10) || isBetween(n, 13, 19)) return 'few';
  2473. if (isIn(n, [2, 12])) return 'two';
  2474. if (isIn(n, [1, 11])) return 'one';
  2475. return 'other';
  2476. }
  2477. };
  2478. var index = locales2rules[lang.replace(/-.*$/, '')];
  2479. if (!(index in pluralRules)) {
  2480. console.warn('plural form unknown for [' + lang + ']');
  2481. return function () {
  2482. return 'other';
  2483. };
  2484. }
  2485. return pluralRules[index];
  2486. }
  2487. gMacros.plural = function (str, param, key, prop) {
  2488. var n = parseFloat(param);
  2489. if (isNaN(n)) return str;
  2490. if (prop != gTextProp) return str;
  2491. if (!gMacros._pluralRules) {
  2492. gMacros._pluralRules = getPluralRules(gLanguage);
  2493. }
  2494. var index = '[' + gMacros._pluralRules(n) + ']';
  2495. if (n === 0 && key + '[zero]' in gL10nData) {
  2496. str = gL10nData[key + '[zero]'][prop];
  2497. } else if (n == 1 && key + '[one]' in gL10nData) {
  2498. str = gL10nData[key + '[one]'][prop];
  2499. } else if (n == 2 && key + '[two]' in gL10nData) {
  2500. str = gL10nData[key + '[two]'][prop];
  2501. } else if (key + index in gL10nData) {
  2502. str = gL10nData[key + index][prop];
  2503. } else if (key + '[other]' in gL10nData) {
  2504. str = gL10nData[key + '[other]'][prop];
  2505. }
  2506. return str;
  2507. };
  2508. function getL10nData(key, args, fallback) {
  2509. var data = gL10nData[key];
  2510. if (!data) {
  2511. console.warn('#' + key + ' is undefined.');
  2512. if (!fallback) {
  2513. return null;
  2514. }
  2515. data = fallback;
  2516. }
  2517. var rv = {};
  2518. for (var prop in data) {
  2519. var str = data[prop];
  2520. str = substIndexes(str, args, key, prop);
  2521. str = substArguments(str, args, key);
  2522. rv[prop] = str;
  2523. }
  2524. return rv;
  2525. }
  2526. function substIndexes(str, args, key, prop) {
  2527. var reIndex = /\{\[\s*([a-zA-Z]+)\(([a-zA-Z]+)\)\s*\]\}/;
  2528. var reMatch = reIndex.exec(str);
  2529. if (!reMatch || !reMatch.length) return str;
  2530. var macroName = reMatch[1];
  2531. var paramName = reMatch[2];
  2532. var param;
  2533. if (args && paramName in args) {
  2534. param = args[paramName];
  2535. } else if (paramName in gL10nData) {
  2536. param = gL10nData[paramName];
  2537. }
  2538. if (macroName in gMacros) {
  2539. var macro = gMacros[macroName];
  2540. str = macro(str, param, key, prop);
  2541. }
  2542. return str;
  2543. }
  2544. function substArguments(str, args, key) {
  2545. var reArgs = /\{\{\s*(.+?)\s*\}\}/g;
  2546. return str.replace(reArgs, function (matched_text, arg) {
  2547. if (args && arg in args) {
  2548. return args[arg];
  2549. }
  2550. if (arg in gL10nData) {
  2551. return gL10nData[arg];
  2552. }
  2553. console.log('argument {{' + arg + '}} for #' + key + ' is undefined.');
  2554. return matched_text;
  2555. });
  2556. }
  2557. function translateElement(element) {
  2558. var l10n = getL10nAttributes(element);
  2559. if (!l10n.id) return;
  2560. var data = getL10nData(l10n.id, l10n.args);
  2561. if (!data) {
  2562. console.warn('#' + l10n.id + ' is undefined.');
  2563. return;
  2564. }
  2565. if (data[gTextProp]) {
  2566. if (getChildElementCount(element) === 0) {
  2567. element[gTextProp] = data[gTextProp];
  2568. } else {
  2569. var children = element.childNodes;
  2570. var found = false;
  2571. for (var i = 0, l = children.length; i < l; i++) {
  2572. if (children[i].nodeType === 3 && /\S/.test(children[i].nodeValue)) {
  2573. if (found) {
  2574. children[i].nodeValue = '';
  2575. } else {
  2576. children[i].nodeValue = data[gTextProp];
  2577. found = true;
  2578. }
  2579. }
  2580. }
  2581. if (!found) {
  2582. var textNode = document.createTextNode(data[gTextProp]);
  2583. element.prepend(textNode);
  2584. }
  2585. }
  2586. delete data[gTextProp];
  2587. }
  2588. for (var k in data) {
  2589. element[k] = data[k];
  2590. }
  2591. }
  2592. function getChildElementCount(element) {
  2593. if (element.children) {
  2594. return element.children.length;
  2595. }
  2596. if (typeof element.childElementCount !== 'undefined') {
  2597. return element.childElementCount;
  2598. }
  2599. var count = 0;
  2600. for (var i = 0; i < element.childNodes.length; i++) {
  2601. count += element.nodeType === 1 ? 1 : 0;
  2602. }
  2603. return count;
  2604. }
  2605. function translateFragment(element) {
  2606. element = element || document.documentElement;
  2607. var children = getTranslatableChildren(element);
  2608. var elementCount = children.length;
  2609. for (var i = 0; i < elementCount; i++) {
  2610. translateElement(children[i]);
  2611. }
  2612. translateElement(element);
  2613. }
  2614. return {
  2615. get: function (key, args, fallbackString) {
  2616. var index = key.lastIndexOf('.');
  2617. var prop = gTextProp;
  2618. if (index > 0) {
  2619. prop = key.substring(index + 1);
  2620. key = key.substring(0, index);
  2621. }
  2622. var fallback;
  2623. if (fallbackString) {
  2624. fallback = {};
  2625. fallback[prop] = fallbackString;
  2626. }
  2627. var data = getL10nData(key, args, fallback);
  2628. if (data && prop in data) {
  2629. return data[prop];
  2630. }
  2631. return '{{' + key + '}}';
  2632. },
  2633. getData: function () {
  2634. return gL10nData;
  2635. },
  2636. getText: function () {
  2637. return gTextData;
  2638. },
  2639. getLanguage: function () {
  2640. return gLanguage;
  2641. },
  2642. setLanguage: function (lang, callback) {
  2643. loadLocale(lang, function () {
  2644. if (callback) callback();
  2645. });
  2646. },
  2647. getDirection: function () {
  2648. var rtlList = ['ar', 'he', 'fa', 'ps', 'ur'];
  2649. var shortCode = gLanguage.split('-', 1)[0];
  2650. return rtlList.indexOf(shortCode) >= 0 ? 'rtl' : 'ltr';
  2651. },
  2652. translate: translateFragment,
  2653. getReadyState: function () {
  2654. return gReadyState;
  2655. },
  2656. ready: function (callback) {
  2657. if (!callback) {
  2658. return;
  2659. } else if (gReadyState == 'complete' || gReadyState == 'interactive') {
  2660. window.setTimeout(function () {
  2661. callback();
  2662. });
  2663. } else if (document.addEventListener) {
  2664. document.addEventListener('localized', function once() {
  2665. document.removeEventListener('localized', once);
  2666. callback();
  2667. });
  2668. }
  2669. }
  2670. };
  2671. }(window, document);
  2672. /***/ }),
  2673. /* 15 */
  2674. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  2675. Object.defineProperty(exports, "__esModule", ({
  2676. value: true
  2677. }));
  2678. exports.PDFFindController = exports.FindState = void 0;
  2679. var _ui_utils = __w_pdfjs_require__(6);
  2680. var _pdfjsLib = __w_pdfjs_require__(3);
  2681. var _pdf_find_utils = __w_pdfjs_require__(16);
  2682. const FindState = {
  2683. FOUND: 0,
  2684. NOT_FOUND: 1,
  2685. WRAPPED: 2,
  2686. PENDING: 3
  2687. };
  2688. exports.FindState = FindState;
  2689. const FIND_TIMEOUT = 250;
  2690. const MATCH_SCROLL_OFFSET_TOP = -50;
  2691. const MATCH_SCROLL_OFFSET_LEFT = -400;
  2692. const CHARACTERS_TO_NORMALIZE = {
  2693. "\u2010": "-",
  2694. "\u2018": "'",
  2695. "\u2019": "'",
  2696. "\u201A": "'",
  2697. "\u201B": "'",
  2698. "\u201C": '"',
  2699. "\u201D": '"',
  2700. "\u201E": '"',
  2701. "\u201F": '"',
  2702. "\u00BC": "1/4",
  2703. "\u00BD": "1/2",
  2704. "\u00BE": "3/4"
  2705. };
  2706. const DIACRITICS_EXCEPTION = new Set([0x3099, 0x309a, 0x094d, 0x09cd, 0x0a4d, 0x0acd, 0x0b4d, 0x0bcd, 0x0c4d, 0x0ccd, 0x0d3b, 0x0d3c, 0x0d4d, 0x0dca, 0x0e3a, 0x0eba, 0x0f84, 0x1039, 0x103a, 0x1714, 0x1734, 0x17d2, 0x1a60, 0x1b44, 0x1baa, 0x1bab, 0x1bf2, 0x1bf3, 0x2d7f, 0xa806, 0xa82c, 0xa8c4, 0xa953, 0xa9c0, 0xaaf6, 0xabed, 0x0c56, 0x0f71, 0x0f72, 0x0f7a, 0x0f7b, 0x0f7c, 0x0f7d, 0x0f80, 0x0f74]);
  2707. let DIACRITICS_EXCEPTION_STR;
  2708. const DIACRITICS_REG_EXP = /\p{M}+/gu;
  2709. const SPECIAL_CHARS_REG_EXP = /([.*+?^${}()|[\]\\])|(\p{P})|(\s+)|(\p{M})|(\p{L})/gu;
  2710. const NOT_DIACRITIC_FROM_END_REG_EXP = /([^\p{M}])\p{M}*$/u;
  2711. const NOT_DIACRITIC_FROM_START_REG_EXP = /^\p{M}*([^\p{M}])/u;
  2712. const SYLLABLES_REG_EXP = /[\uAC00-\uD7AF\uFA6C\uFACF-\uFAD1\uFAD5-\uFAD7]+/g;
  2713. const SYLLABLES_LENGTHS = new Map();
  2714. const FIRST_CHAR_SYLLABLES_REG_EXP = "[\\u1100-\\u1112\\ud7a4-\\ud7af\\ud84a\\ud84c\\ud850\\ud854\\ud857\\ud85f]";
  2715. const NFKC_CHARS_TO_NORMALIZE = new Map();
  2716. let noSyllablesRegExp = null;
  2717. let withSyllablesRegExp = null;
  2718. function normalize(text) {
  2719. const syllablePositions = [];
  2720. let m;
  2721. while ((m = SYLLABLES_REG_EXP.exec(text)) !== null) {
  2722. let {
  2723. index
  2724. } = m;
  2725. for (const char of m[0]) {
  2726. let len = SYLLABLES_LENGTHS.get(char);
  2727. if (!len) {
  2728. len = char.normalize("NFD").length;
  2729. SYLLABLES_LENGTHS.set(char, len);
  2730. }
  2731. syllablePositions.push([len, index++]);
  2732. }
  2733. }
  2734. let normalizationRegex;
  2735. if (syllablePositions.length === 0 && noSyllablesRegExp) {
  2736. normalizationRegex = noSyllablesRegExp;
  2737. } else if (syllablePositions.length > 0 && withSyllablesRegExp) {
  2738. normalizationRegex = withSyllablesRegExp;
  2739. } else {
  2740. const replace = Object.keys(CHARACTERS_TO_NORMALIZE).join("");
  2741. const toNormalizeWithNFKC = "\u2460-\u2473" + "\u24b6-\u24ff" + "\u3244-\u32bf" + "\u32d0-\u32fe" + "\uff00-\uffef";
  2742. const regexp = `([${replace}])|([${toNormalizeWithNFKC}])|(\\p{M}+(?:-\\n)?)|(\\S-\\n)|(\\p{Ideographic}\\n)|(\\n)`;
  2743. if (syllablePositions.length === 0) {
  2744. normalizationRegex = noSyllablesRegExp = new RegExp(regexp + "|(\\u0000)", "gum");
  2745. } else {
  2746. normalizationRegex = withSyllablesRegExp = new RegExp(regexp + `|(${FIRST_CHAR_SYLLABLES_REG_EXP})`, "gum");
  2747. }
  2748. }
  2749. const rawDiacriticsPositions = [];
  2750. while ((m = DIACRITICS_REG_EXP.exec(text)) !== null) {
  2751. rawDiacriticsPositions.push([m[0].length, m.index]);
  2752. }
  2753. let normalized = text.normalize("NFD");
  2754. const positions = [[0, 0]];
  2755. let rawDiacriticsIndex = 0;
  2756. let syllableIndex = 0;
  2757. let shift = 0;
  2758. let shiftOrigin = 0;
  2759. let eol = 0;
  2760. let hasDiacritics = false;
  2761. normalized = normalized.replace(normalizationRegex, (match, p1, p2, p3, p4, p5, p6, p7, i) => {
  2762. i -= shiftOrigin;
  2763. if (p1) {
  2764. const replacement = CHARACTERS_TO_NORMALIZE[p1];
  2765. const jj = replacement.length;
  2766. for (let j = 1; j < jj; j++) {
  2767. positions.push([i - shift + j, shift - j]);
  2768. }
  2769. shift -= jj - 1;
  2770. return replacement;
  2771. }
  2772. if (p2) {
  2773. let replacement = NFKC_CHARS_TO_NORMALIZE.get(p2);
  2774. if (!replacement) {
  2775. replacement = p2.normalize("NFKC");
  2776. NFKC_CHARS_TO_NORMALIZE.set(p2, replacement);
  2777. }
  2778. const jj = replacement.length;
  2779. for (let j = 1; j < jj; j++) {
  2780. positions.push([i - shift + j, shift - j]);
  2781. }
  2782. shift -= jj - 1;
  2783. return replacement;
  2784. }
  2785. if (p3) {
  2786. const hasTrailingDashEOL = p3.endsWith("\n");
  2787. const len = hasTrailingDashEOL ? p3.length - 2 : p3.length;
  2788. hasDiacritics = true;
  2789. let jj = len;
  2790. if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) {
  2791. jj -= rawDiacriticsPositions[rawDiacriticsIndex][0];
  2792. ++rawDiacriticsIndex;
  2793. }
  2794. for (let j = 1; j <= jj; j++) {
  2795. positions.push([i - 1 - shift + j, shift - j]);
  2796. }
  2797. shift -= jj;
  2798. shiftOrigin += jj;
  2799. if (hasTrailingDashEOL) {
  2800. i += len - 1;
  2801. positions.push([i - shift + 1, 1 + shift]);
  2802. shift += 1;
  2803. shiftOrigin += 1;
  2804. eol += 1;
  2805. return p3.slice(0, len);
  2806. }
  2807. return p3;
  2808. }
  2809. if (p4) {
  2810. positions.push([i - shift + 1, 1 + shift]);
  2811. shift += 1;
  2812. shiftOrigin += 1;
  2813. eol += 1;
  2814. return p4.charAt(0);
  2815. }
  2816. if (p5) {
  2817. positions.push([i - shift + 1, shift]);
  2818. shiftOrigin += 1;
  2819. eol += 1;
  2820. return p5.charAt(0);
  2821. }
  2822. if (p6) {
  2823. positions.push([i - shift + 1, shift - 1]);
  2824. shift -= 1;
  2825. shiftOrigin += 1;
  2826. eol += 1;
  2827. return " ";
  2828. }
  2829. if (i + eol === syllablePositions[syllableIndex]?.[1]) {
  2830. const newCharLen = syllablePositions[syllableIndex][0] - 1;
  2831. ++syllableIndex;
  2832. for (let j = 1; j <= newCharLen; j++) {
  2833. positions.push([i - (shift - j), shift - j]);
  2834. }
  2835. shift -= newCharLen;
  2836. shiftOrigin += newCharLen;
  2837. }
  2838. return p7;
  2839. });
  2840. positions.push([normalized.length, shift]);
  2841. return [normalized, positions, hasDiacritics];
  2842. }
  2843. function getOriginalIndex(diffs, pos, len) {
  2844. if (!diffs) {
  2845. return [pos, len];
  2846. }
  2847. const start = pos;
  2848. const end = pos + len;
  2849. let i = (0, _ui_utils.binarySearchFirstItem)(diffs, x => x[0] >= start);
  2850. if (diffs[i][0] > start) {
  2851. --i;
  2852. }
  2853. let j = (0, _ui_utils.binarySearchFirstItem)(diffs, x => x[0] >= end, i);
  2854. if (diffs[j][0] > end) {
  2855. --j;
  2856. }
  2857. return [start + diffs[i][1], len + diffs[j][1] - diffs[i][1]];
  2858. }
  2859. class PDFFindController {
  2860. constructor({
  2861. linkService,
  2862. eventBus
  2863. }) {
  2864. this._linkService = linkService;
  2865. this._eventBus = eventBus;
  2866. this.#reset();
  2867. eventBus._on("find", this.#onFind.bind(this));
  2868. eventBus._on("findbarclose", this.#onFindBarClose.bind(this));
  2869. }
  2870. get highlightMatches() {
  2871. return this._highlightMatches;
  2872. }
  2873. get pageMatches() {
  2874. return this._pageMatches;
  2875. }
  2876. get pageMatchesLength() {
  2877. return this._pageMatchesLength;
  2878. }
  2879. get selected() {
  2880. return this._selected;
  2881. }
  2882. get state() {
  2883. return this._state;
  2884. }
  2885. setDocument(pdfDocument) {
  2886. if (this._pdfDocument) {
  2887. this.#reset();
  2888. }
  2889. if (!pdfDocument) {
  2890. return;
  2891. }
  2892. this._pdfDocument = pdfDocument;
  2893. this._firstPageCapability.resolve();
  2894. }
  2895. #onFind(state) {
  2896. if (!state) {
  2897. return;
  2898. }
  2899. const pdfDocument = this._pdfDocument;
  2900. const {
  2901. type
  2902. } = state;
  2903. if (this._state === null || this.#shouldDirtyMatch(state)) {
  2904. this._dirtyMatch = true;
  2905. }
  2906. this._state = state;
  2907. if (type !== "highlightallchange") {
  2908. this.#updateUIState(FindState.PENDING);
  2909. }
  2910. this._firstPageCapability.promise.then(() => {
  2911. if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) {
  2912. return;
  2913. }
  2914. this.#extractText();
  2915. const findbarClosed = !this._highlightMatches;
  2916. const pendingTimeout = !!this._findTimeout;
  2917. if (this._findTimeout) {
  2918. clearTimeout(this._findTimeout);
  2919. this._findTimeout = null;
  2920. }
  2921. if (!type) {
  2922. this._findTimeout = setTimeout(() => {
  2923. this.#nextMatch();
  2924. this._findTimeout = null;
  2925. }, FIND_TIMEOUT);
  2926. } else if (this._dirtyMatch) {
  2927. this.#nextMatch();
  2928. } else if (type === "again") {
  2929. this.#nextMatch();
  2930. if (findbarClosed && this._state.highlightAll) {
  2931. this.#updateAllPages();
  2932. }
  2933. } else if (type === "highlightallchange") {
  2934. if (pendingTimeout) {
  2935. this.#nextMatch();
  2936. } else {
  2937. this._highlightMatches = true;
  2938. }
  2939. this.#updateAllPages();
  2940. } else {
  2941. this.#nextMatch();
  2942. }
  2943. });
  2944. }
  2945. scrollMatchIntoView({
  2946. element = null,
  2947. selectedLeft = 0,
  2948. pageIndex = -1,
  2949. matchIndex = -1
  2950. }) {
  2951. if (!this._scrollMatches || !element) {
  2952. return;
  2953. } else if (matchIndex === -1 || matchIndex !== this._selected.matchIdx) {
  2954. return;
  2955. } else if (pageIndex === -1 || pageIndex !== this._selected.pageIdx) {
  2956. return;
  2957. }
  2958. this._scrollMatches = false;
  2959. const spot = {
  2960. top: MATCH_SCROLL_OFFSET_TOP,
  2961. left: selectedLeft + MATCH_SCROLL_OFFSET_LEFT
  2962. };
  2963. (0, _ui_utils.scrollIntoView)(element, spot, true);
  2964. }
  2965. #reset() {
  2966. this._highlightMatches = false;
  2967. this._scrollMatches = false;
  2968. this._pdfDocument = null;
  2969. this._pageMatches = [];
  2970. this._pageMatchesLength = [];
  2971. this._state = null;
  2972. this._selected = {
  2973. pageIdx: -1,
  2974. matchIdx: -1
  2975. };
  2976. this._offset = {
  2977. pageIdx: null,
  2978. matchIdx: null,
  2979. wrapped: false
  2980. };
  2981. this._extractTextPromises = [];
  2982. this._pageContents = [];
  2983. this._pageDiffs = [];
  2984. this._hasDiacritics = [];
  2985. this._matchesCountTotal = 0;
  2986. this._pagesToSearch = null;
  2987. this._pendingFindMatches = new Set();
  2988. this._resumePageIdx = null;
  2989. this._dirtyMatch = false;
  2990. clearTimeout(this._findTimeout);
  2991. this._findTimeout = null;
  2992. this._firstPageCapability = (0, _pdfjsLib.createPromiseCapability)();
  2993. }
  2994. get #query() {
  2995. if (this._state.query !== this._rawQuery) {
  2996. this._rawQuery = this._state.query;
  2997. [this._normalizedQuery] = normalize(this._state.query);
  2998. }
  2999. return this._normalizedQuery;
  3000. }
  3001. #shouldDirtyMatch(state) {
  3002. if (state.query !== this._state.query) {
  3003. return true;
  3004. }
  3005. switch (state.type) {
  3006. case "again":
  3007. const pageNumber = this._selected.pageIdx + 1;
  3008. const linkService = this._linkService;
  3009. if (pageNumber >= 1 && pageNumber <= linkService.pagesCount && pageNumber !== linkService.page && !linkService.isPageVisible(pageNumber)) {
  3010. return true;
  3011. }
  3012. return false;
  3013. case "highlightallchange":
  3014. return false;
  3015. }
  3016. return true;
  3017. }
  3018. #isEntireWord(content, startIdx, length) {
  3019. let match = content.slice(0, startIdx).match(NOT_DIACRITIC_FROM_END_REG_EXP);
  3020. if (match) {
  3021. const first = content.charCodeAt(startIdx);
  3022. const limit = match[1].charCodeAt(0);
  3023. if ((0, _pdf_find_utils.getCharacterType)(first) === (0, _pdf_find_utils.getCharacterType)(limit)) {
  3024. return false;
  3025. }
  3026. }
  3027. match = content.slice(startIdx + length).match(NOT_DIACRITIC_FROM_START_REG_EXP);
  3028. if (match) {
  3029. const last = content.charCodeAt(startIdx + length - 1);
  3030. const limit = match[1].charCodeAt(0);
  3031. if ((0, _pdf_find_utils.getCharacterType)(last) === (0, _pdf_find_utils.getCharacterType)(limit)) {
  3032. return false;
  3033. }
  3034. }
  3035. return true;
  3036. }
  3037. #calculateRegExpMatch(query, entireWord, pageIndex, pageContent) {
  3038. const matches = [],
  3039. matchesLength = [];
  3040. const diffs = this._pageDiffs[pageIndex];
  3041. let match;
  3042. while ((match = query.exec(pageContent)) !== null) {
  3043. if (entireWord && !this.#isEntireWord(pageContent, match.index, match[0].length)) {
  3044. continue;
  3045. }
  3046. const [matchPos, matchLen] = getOriginalIndex(diffs, match.index, match[0].length);
  3047. if (matchLen) {
  3048. matches.push(matchPos);
  3049. matchesLength.push(matchLen);
  3050. }
  3051. }
  3052. this._pageMatches[pageIndex] = matches;
  3053. this._pageMatchesLength[pageIndex] = matchesLength;
  3054. }
  3055. #convertToRegExpString(query, hasDiacritics) {
  3056. const {
  3057. matchDiacritics
  3058. } = this._state;
  3059. let isUnicode = false;
  3060. query = query.replace(SPECIAL_CHARS_REG_EXP, (match, p1, p2, p3, p4, p5) => {
  3061. if (p1) {
  3062. return `[ ]*\\${p1}[ ]*`;
  3063. }
  3064. if (p2) {
  3065. return `[ ]*${p2}[ ]*`;
  3066. }
  3067. if (p3) {
  3068. return "[ ]+";
  3069. }
  3070. if (matchDiacritics) {
  3071. return p4 || p5;
  3072. }
  3073. if (p4) {
  3074. return DIACRITICS_EXCEPTION.has(p4.charCodeAt(0)) ? p4 : "";
  3075. }
  3076. if (hasDiacritics) {
  3077. isUnicode = true;
  3078. return `${p5}\\p{M}*`;
  3079. }
  3080. return p5;
  3081. });
  3082. const trailingSpaces = "[ ]*";
  3083. if (query.endsWith(trailingSpaces)) {
  3084. query = query.slice(0, query.length - trailingSpaces.length);
  3085. }
  3086. if (matchDiacritics) {
  3087. if (hasDiacritics) {
  3088. DIACRITICS_EXCEPTION_STR ||= String.fromCharCode(...DIACRITICS_EXCEPTION);
  3089. isUnicode = true;
  3090. query = `${query}(?=[${DIACRITICS_EXCEPTION_STR}]|[^\\p{M}]|$)`;
  3091. }
  3092. }
  3093. return [isUnicode, query];
  3094. }
  3095. #calculateMatch(pageIndex) {
  3096. let query = this.#query;
  3097. if (query.length === 0) {
  3098. return;
  3099. }
  3100. const {
  3101. caseSensitive,
  3102. entireWord,
  3103. phraseSearch
  3104. } = this._state;
  3105. const pageContent = this._pageContents[pageIndex];
  3106. const hasDiacritics = this._hasDiacritics[pageIndex];
  3107. let isUnicode = false;
  3108. if (phraseSearch) {
  3109. [isUnicode, query] = this.#convertToRegExpString(query, hasDiacritics);
  3110. } else {
  3111. const match = query.match(/\S+/g);
  3112. if (match) {
  3113. query = match.sort().reverse().map(q => {
  3114. const [isUnicodePart, queryPart] = this.#convertToRegExpString(q, hasDiacritics);
  3115. isUnicode ||= isUnicodePart;
  3116. return `(${queryPart})`;
  3117. }).join("|");
  3118. }
  3119. }
  3120. const flags = `g${isUnicode ? "u" : ""}${caseSensitive ? "" : "i"}`;
  3121. query = new RegExp(query, flags);
  3122. this.#calculateRegExpMatch(query, entireWord, pageIndex, pageContent);
  3123. if (this._state.highlightAll) {
  3124. this.#updatePage(pageIndex);
  3125. }
  3126. if (this._resumePageIdx === pageIndex) {
  3127. this._resumePageIdx = null;
  3128. this.#nextPageMatch();
  3129. }
  3130. const pageMatchesCount = this._pageMatches[pageIndex].length;
  3131. if (pageMatchesCount > 0) {
  3132. this._matchesCountTotal += pageMatchesCount;
  3133. this.#updateUIResultsCount();
  3134. }
  3135. }
  3136. #extractText() {
  3137. if (this._extractTextPromises.length > 0) {
  3138. return;
  3139. }
  3140. let promise = Promise.resolve();
  3141. for (let i = 0, ii = this._linkService.pagesCount; i < ii; i++) {
  3142. const extractTextCapability = (0, _pdfjsLib.createPromiseCapability)();
  3143. this._extractTextPromises[i] = extractTextCapability.promise;
  3144. promise = promise.then(() => {
  3145. return this._pdfDocument.getPage(i + 1).then(pdfPage => {
  3146. return pdfPage.getTextContent();
  3147. }).then(textContent => {
  3148. const strBuf = [];
  3149. for (const textItem of textContent.items) {
  3150. strBuf.push(textItem.str);
  3151. if (textItem.hasEOL) {
  3152. strBuf.push("\n");
  3153. }
  3154. }
  3155. [this._pageContents[i], this._pageDiffs[i], this._hasDiacritics[i]] = normalize(strBuf.join(""));
  3156. extractTextCapability.resolve();
  3157. }, reason => {
  3158. console.error(`Unable to get text content for page ${i + 1}`, reason);
  3159. this._pageContents[i] = "";
  3160. this._pageDiffs[i] = null;
  3161. this._hasDiacritics[i] = false;
  3162. extractTextCapability.resolve();
  3163. });
  3164. });
  3165. }
  3166. }
  3167. #updatePage(index) {
  3168. if (this._scrollMatches && this._selected.pageIdx === index) {
  3169. this._linkService.page = index + 1;
  3170. }
  3171. this._eventBus.dispatch("updatetextlayermatches", {
  3172. source: this,
  3173. pageIndex: index
  3174. });
  3175. }
  3176. #updateAllPages() {
  3177. this._eventBus.dispatch("updatetextlayermatches", {
  3178. source: this,
  3179. pageIndex: -1
  3180. });
  3181. }
  3182. #nextMatch() {
  3183. const previous = this._state.findPrevious;
  3184. const currentPageIndex = this._linkService.page - 1;
  3185. const numPages = this._linkService.pagesCount;
  3186. this._highlightMatches = true;
  3187. if (this._dirtyMatch) {
  3188. this._dirtyMatch = false;
  3189. this._selected.pageIdx = this._selected.matchIdx = -1;
  3190. this._offset.pageIdx = currentPageIndex;
  3191. this._offset.matchIdx = null;
  3192. this._offset.wrapped = false;
  3193. this._resumePageIdx = null;
  3194. this._pageMatches.length = 0;
  3195. this._pageMatchesLength.length = 0;
  3196. this._matchesCountTotal = 0;
  3197. this.#updateAllPages();
  3198. for (let i = 0; i < numPages; i++) {
  3199. if (this._pendingFindMatches.has(i)) {
  3200. continue;
  3201. }
  3202. this._pendingFindMatches.add(i);
  3203. this._extractTextPromises[i].then(() => {
  3204. this._pendingFindMatches.delete(i);
  3205. this.#calculateMatch(i);
  3206. });
  3207. }
  3208. }
  3209. if (this.#query === "") {
  3210. this.#updateUIState(FindState.FOUND);
  3211. return;
  3212. }
  3213. if (this._resumePageIdx) {
  3214. return;
  3215. }
  3216. const offset = this._offset;
  3217. this._pagesToSearch = numPages;
  3218. if (offset.matchIdx !== null) {
  3219. const numPageMatches = this._pageMatches[offset.pageIdx].length;
  3220. if (!previous && offset.matchIdx + 1 < numPageMatches || previous && offset.matchIdx > 0) {
  3221. offset.matchIdx = previous ? offset.matchIdx - 1 : offset.matchIdx + 1;
  3222. this.#updateMatch(true);
  3223. return;
  3224. }
  3225. this.#advanceOffsetPage(previous);
  3226. }
  3227. this.#nextPageMatch();
  3228. }
  3229. #matchesReady(matches) {
  3230. const offset = this._offset;
  3231. const numMatches = matches.length;
  3232. const previous = this._state.findPrevious;
  3233. if (numMatches) {
  3234. offset.matchIdx = previous ? numMatches - 1 : 0;
  3235. this.#updateMatch(true);
  3236. return true;
  3237. }
  3238. this.#advanceOffsetPage(previous);
  3239. if (offset.wrapped) {
  3240. offset.matchIdx = null;
  3241. if (this._pagesToSearch < 0) {
  3242. this.#updateMatch(false);
  3243. return true;
  3244. }
  3245. }
  3246. return false;
  3247. }
  3248. #nextPageMatch() {
  3249. if (this._resumePageIdx !== null) {
  3250. console.error("There can only be one pending page.");
  3251. }
  3252. let matches = null;
  3253. do {
  3254. const pageIdx = this._offset.pageIdx;
  3255. matches = this._pageMatches[pageIdx];
  3256. if (!matches) {
  3257. this._resumePageIdx = pageIdx;
  3258. break;
  3259. }
  3260. } while (!this.#matchesReady(matches));
  3261. }
  3262. #advanceOffsetPage(previous) {
  3263. const offset = this._offset;
  3264. const numPages = this._linkService.pagesCount;
  3265. offset.pageIdx = previous ? offset.pageIdx - 1 : offset.pageIdx + 1;
  3266. offset.matchIdx = null;
  3267. this._pagesToSearch--;
  3268. if (offset.pageIdx >= numPages || offset.pageIdx < 0) {
  3269. offset.pageIdx = previous ? numPages - 1 : 0;
  3270. offset.wrapped = true;
  3271. }
  3272. }
  3273. #updateMatch(found = false) {
  3274. let state = FindState.NOT_FOUND;
  3275. const wrapped = this._offset.wrapped;
  3276. this._offset.wrapped = false;
  3277. if (found) {
  3278. const previousPage = this._selected.pageIdx;
  3279. this._selected.pageIdx = this._offset.pageIdx;
  3280. this._selected.matchIdx = this._offset.matchIdx;
  3281. state = wrapped ? FindState.WRAPPED : FindState.FOUND;
  3282. if (previousPage !== -1 && previousPage !== this._selected.pageIdx) {
  3283. this.#updatePage(previousPage);
  3284. }
  3285. }
  3286. this.#updateUIState(state, this._state.findPrevious);
  3287. if (this._selected.pageIdx !== -1) {
  3288. this._scrollMatches = true;
  3289. this.#updatePage(this._selected.pageIdx);
  3290. }
  3291. }
  3292. #onFindBarClose(evt) {
  3293. const pdfDocument = this._pdfDocument;
  3294. this._firstPageCapability.promise.then(() => {
  3295. if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) {
  3296. return;
  3297. }
  3298. if (this._findTimeout) {
  3299. clearTimeout(this._findTimeout);
  3300. this._findTimeout = null;
  3301. }
  3302. if (this._resumePageIdx) {
  3303. this._resumePageIdx = null;
  3304. this._dirtyMatch = true;
  3305. }
  3306. this.#updateUIState(FindState.FOUND);
  3307. this._highlightMatches = false;
  3308. this.#updateAllPages();
  3309. });
  3310. }
  3311. #requestMatchesCount() {
  3312. const {
  3313. pageIdx,
  3314. matchIdx
  3315. } = this._selected;
  3316. let current = 0,
  3317. total = this._matchesCountTotal;
  3318. if (matchIdx !== -1) {
  3319. for (let i = 0; i < pageIdx; i++) {
  3320. current += this._pageMatches[i]?.length || 0;
  3321. }
  3322. current += matchIdx + 1;
  3323. }
  3324. if (current < 1 || current > total) {
  3325. current = total = 0;
  3326. }
  3327. return {
  3328. current,
  3329. total
  3330. };
  3331. }
  3332. #updateUIResultsCount() {
  3333. this._eventBus.dispatch("updatefindmatchescount", {
  3334. source: this,
  3335. matchesCount: this.#requestMatchesCount()
  3336. });
  3337. }
  3338. #updateUIState(state, previous = false) {
  3339. this._eventBus.dispatch("updatefindcontrolstate", {
  3340. source: this,
  3341. state,
  3342. previous,
  3343. matchesCount: this.#requestMatchesCount(),
  3344. rawQuery: this._state?.query ?? null
  3345. });
  3346. }
  3347. }
  3348. exports.PDFFindController = PDFFindController;
  3349. /***/ }),
  3350. /* 16 */
  3351. /***/ ((__unused_webpack_module, exports) => {
  3352. Object.defineProperty(exports, "__esModule", ({
  3353. value: true
  3354. }));
  3355. exports.CharacterType = void 0;
  3356. exports.getCharacterType = getCharacterType;
  3357. const CharacterType = {
  3358. SPACE: 0,
  3359. ALPHA_LETTER: 1,
  3360. PUNCT: 2,
  3361. HAN_LETTER: 3,
  3362. KATAKANA_LETTER: 4,
  3363. HIRAGANA_LETTER: 5,
  3364. HALFWIDTH_KATAKANA_LETTER: 6,
  3365. THAI_LETTER: 7
  3366. };
  3367. exports.CharacterType = CharacterType;
  3368. function isAlphabeticalScript(charCode) {
  3369. return charCode < 0x2e80;
  3370. }
  3371. function isAscii(charCode) {
  3372. return (charCode & 0xff80) === 0;
  3373. }
  3374. function isAsciiAlpha(charCode) {
  3375. return charCode >= 0x61 && charCode <= 0x7a || charCode >= 0x41 && charCode <= 0x5a;
  3376. }
  3377. function isAsciiDigit(charCode) {
  3378. return charCode >= 0x30 && charCode <= 0x39;
  3379. }
  3380. function isAsciiSpace(charCode) {
  3381. return charCode === 0x20 || charCode === 0x09 || charCode === 0x0d || charCode === 0x0a;
  3382. }
  3383. function isHan(charCode) {
  3384. return charCode >= 0x3400 && charCode <= 0x9fff || charCode >= 0xf900 && charCode <= 0xfaff;
  3385. }
  3386. function isKatakana(charCode) {
  3387. return charCode >= 0x30a0 && charCode <= 0x30ff;
  3388. }
  3389. function isHiragana(charCode) {
  3390. return charCode >= 0x3040 && charCode <= 0x309f;
  3391. }
  3392. function isHalfwidthKatakana(charCode) {
  3393. return charCode >= 0xff60 && charCode <= 0xff9f;
  3394. }
  3395. function isThai(charCode) {
  3396. return (charCode & 0xff80) === 0x0e00;
  3397. }
  3398. function getCharacterType(charCode) {
  3399. if (isAlphabeticalScript(charCode)) {
  3400. if (isAscii(charCode)) {
  3401. if (isAsciiSpace(charCode)) {
  3402. return CharacterType.SPACE;
  3403. } else if (isAsciiAlpha(charCode) || isAsciiDigit(charCode) || charCode === 0x5f) {
  3404. return CharacterType.ALPHA_LETTER;
  3405. }
  3406. return CharacterType.PUNCT;
  3407. } else if (isThai(charCode)) {
  3408. return CharacterType.THAI_LETTER;
  3409. } else if (charCode === 0xa0) {
  3410. return CharacterType.SPACE;
  3411. }
  3412. return CharacterType.ALPHA_LETTER;
  3413. }
  3414. if (isHan(charCode)) {
  3415. return CharacterType.HAN_LETTER;
  3416. } else if (isKatakana(charCode)) {
  3417. return CharacterType.KATAKANA_LETTER;
  3418. } else if (isHiragana(charCode)) {
  3419. return CharacterType.HIRAGANA_LETTER;
  3420. } else if (isHalfwidthKatakana(charCode)) {
  3421. return CharacterType.HALFWIDTH_KATAKANA_LETTER;
  3422. }
  3423. return CharacterType.ALPHA_LETTER;
  3424. }
  3425. /***/ }),
  3426. /* 17 */
  3427. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3428. Object.defineProperty(exports, "__esModule", ({
  3429. value: true
  3430. }));
  3431. exports.PDFHistory = void 0;
  3432. exports.isDestArraysEqual = isDestArraysEqual;
  3433. exports.isDestHashesEqual = isDestHashesEqual;
  3434. var _ui_utils = __w_pdfjs_require__(6);
  3435. var _event_utils = __w_pdfjs_require__(12);
  3436. const HASH_CHANGE_TIMEOUT = 1000;
  3437. const POSITION_UPDATED_THRESHOLD = 50;
  3438. const UPDATE_VIEWAREA_TIMEOUT = 1000;
  3439. function getCurrentHash() {
  3440. return document.location.hash;
  3441. }
  3442. class PDFHistory {
  3443. constructor({
  3444. linkService,
  3445. eventBus
  3446. }) {
  3447. this.linkService = linkService;
  3448. this.eventBus = eventBus;
  3449. this._initialized = false;
  3450. this._fingerprint = "";
  3451. this.reset();
  3452. this._boundEvents = null;
  3453. this.eventBus._on("pagesinit", () => {
  3454. this._isPagesLoaded = false;
  3455. this.eventBus._on("pagesloaded", evt => {
  3456. this._isPagesLoaded = !!evt.pagesCount;
  3457. }, {
  3458. once: true
  3459. });
  3460. });
  3461. }
  3462. initialize({
  3463. fingerprint,
  3464. resetHistory = false,
  3465. updateUrl = false
  3466. }) {
  3467. if (!fingerprint || typeof fingerprint !== "string") {
  3468. console.error('PDFHistory.initialize: The "fingerprint" must be a non-empty string.');
  3469. return;
  3470. }
  3471. if (this._initialized) {
  3472. this.reset();
  3473. }
  3474. const reInitialized = this._fingerprint !== "" && this._fingerprint !== fingerprint;
  3475. this._fingerprint = fingerprint;
  3476. this._updateUrl = updateUrl === true;
  3477. this._initialized = true;
  3478. this._bindEvents();
  3479. const state = window.history.state;
  3480. this._popStateInProgress = false;
  3481. this._blockHashChange = 0;
  3482. this._currentHash = getCurrentHash();
  3483. this._numPositionUpdates = 0;
  3484. this._uid = this._maxUid = 0;
  3485. this._destination = null;
  3486. this._position = null;
  3487. if (!this._isValidState(state, true) || resetHistory) {
  3488. const {
  3489. hash,
  3490. page,
  3491. rotation
  3492. } = this._parseCurrentHash(true);
  3493. if (!hash || reInitialized || resetHistory) {
  3494. this._pushOrReplaceState(null, true);
  3495. return;
  3496. }
  3497. this._pushOrReplaceState({
  3498. hash,
  3499. page,
  3500. rotation
  3501. }, true);
  3502. return;
  3503. }
  3504. const destination = state.destination;
  3505. this._updateInternalState(destination, state.uid, true);
  3506. if (destination.rotation !== undefined) {
  3507. this._initialRotation = destination.rotation;
  3508. }
  3509. if (destination.dest) {
  3510. this._initialBookmark = JSON.stringify(destination.dest);
  3511. this._destination.page = null;
  3512. } else if (destination.hash) {
  3513. this._initialBookmark = destination.hash;
  3514. } else if (destination.page) {
  3515. this._initialBookmark = `page=${destination.page}`;
  3516. }
  3517. }
  3518. reset() {
  3519. if (this._initialized) {
  3520. this._pageHide();
  3521. this._initialized = false;
  3522. this._unbindEvents();
  3523. }
  3524. if (this._updateViewareaTimeout) {
  3525. clearTimeout(this._updateViewareaTimeout);
  3526. this._updateViewareaTimeout = null;
  3527. }
  3528. this._initialBookmark = null;
  3529. this._initialRotation = null;
  3530. }
  3531. push({
  3532. namedDest = null,
  3533. explicitDest,
  3534. pageNumber
  3535. }) {
  3536. if (!this._initialized) {
  3537. return;
  3538. }
  3539. if (namedDest && typeof namedDest !== "string") {
  3540. console.error("PDFHistory.push: " + `"${namedDest}" is not a valid namedDest parameter.`);
  3541. return;
  3542. } else if (!Array.isArray(explicitDest)) {
  3543. console.error("PDFHistory.push: " + `"${explicitDest}" is not a valid explicitDest parameter.`);
  3544. return;
  3545. } else if (!this._isValidPage(pageNumber)) {
  3546. if (pageNumber !== null || this._destination) {
  3547. console.error("PDFHistory.push: " + `"${pageNumber}" is not a valid pageNumber parameter.`);
  3548. return;
  3549. }
  3550. }
  3551. const hash = namedDest || JSON.stringify(explicitDest);
  3552. if (!hash) {
  3553. return;
  3554. }
  3555. let forceReplace = false;
  3556. if (this._destination && (isDestHashesEqual(this._destination.hash, hash) || isDestArraysEqual(this._destination.dest, explicitDest))) {
  3557. if (this._destination.page) {
  3558. return;
  3559. }
  3560. forceReplace = true;
  3561. }
  3562. if (this._popStateInProgress && !forceReplace) {
  3563. return;
  3564. }
  3565. this._pushOrReplaceState({
  3566. dest: explicitDest,
  3567. hash,
  3568. page: pageNumber,
  3569. rotation: this.linkService.rotation
  3570. }, forceReplace);
  3571. if (!this._popStateInProgress) {
  3572. this._popStateInProgress = true;
  3573. Promise.resolve().then(() => {
  3574. this._popStateInProgress = false;
  3575. });
  3576. }
  3577. }
  3578. pushPage(pageNumber) {
  3579. if (!this._initialized) {
  3580. return;
  3581. }
  3582. if (!this._isValidPage(pageNumber)) {
  3583. console.error(`PDFHistory.pushPage: "${pageNumber}" is not a valid page number.`);
  3584. return;
  3585. }
  3586. if (this._destination?.page === pageNumber) {
  3587. return;
  3588. }
  3589. if (this._popStateInProgress) {
  3590. return;
  3591. }
  3592. this._pushOrReplaceState({
  3593. dest: null,
  3594. hash: `page=${pageNumber}`,
  3595. page: pageNumber,
  3596. rotation: this.linkService.rotation
  3597. });
  3598. if (!this._popStateInProgress) {
  3599. this._popStateInProgress = true;
  3600. Promise.resolve().then(() => {
  3601. this._popStateInProgress = false;
  3602. });
  3603. }
  3604. }
  3605. pushCurrentPosition() {
  3606. if (!this._initialized || this._popStateInProgress) {
  3607. return;
  3608. }
  3609. this._tryPushCurrentPosition();
  3610. }
  3611. back() {
  3612. if (!this._initialized || this._popStateInProgress) {
  3613. return;
  3614. }
  3615. const state = window.history.state;
  3616. if (this._isValidState(state) && state.uid > 0) {
  3617. window.history.back();
  3618. }
  3619. }
  3620. forward() {
  3621. if (!this._initialized || this._popStateInProgress) {
  3622. return;
  3623. }
  3624. const state = window.history.state;
  3625. if (this._isValidState(state) && state.uid < this._maxUid) {
  3626. window.history.forward();
  3627. }
  3628. }
  3629. get popStateInProgress() {
  3630. return this._initialized && (this._popStateInProgress || this._blockHashChange > 0);
  3631. }
  3632. get initialBookmark() {
  3633. return this._initialized ? this._initialBookmark : null;
  3634. }
  3635. get initialRotation() {
  3636. return this._initialized ? this._initialRotation : null;
  3637. }
  3638. _pushOrReplaceState(destination, forceReplace = false) {
  3639. const shouldReplace = forceReplace || !this._destination;
  3640. const newState = {
  3641. fingerprint: this._fingerprint,
  3642. uid: shouldReplace ? this._uid : this._uid + 1,
  3643. destination
  3644. };
  3645. this._updateInternalState(destination, newState.uid);
  3646. let newUrl;
  3647. if (this._updateUrl && destination?.hash) {
  3648. const baseUrl = document.location.href.split("#")[0];
  3649. if (!baseUrl.startsWith("file://")) {
  3650. newUrl = `${baseUrl}#${destination.hash}`;
  3651. }
  3652. }
  3653. if (shouldReplace) {
  3654. window.history.replaceState(newState, "", newUrl);
  3655. } else {
  3656. window.history.pushState(newState, "", newUrl);
  3657. }
  3658. }
  3659. _tryPushCurrentPosition(temporary = false) {
  3660. if (!this._position) {
  3661. return;
  3662. }
  3663. let position = this._position;
  3664. if (temporary) {
  3665. position = Object.assign(Object.create(null), this._position);
  3666. position.temporary = true;
  3667. }
  3668. if (!this._destination) {
  3669. this._pushOrReplaceState(position);
  3670. return;
  3671. }
  3672. if (this._destination.temporary) {
  3673. this._pushOrReplaceState(position, true);
  3674. return;
  3675. }
  3676. if (this._destination.hash === position.hash) {
  3677. return;
  3678. }
  3679. if (!this._destination.page && (POSITION_UPDATED_THRESHOLD <= 0 || this._numPositionUpdates <= POSITION_UPDATED_THRESHOLD)) {
  3680. return;
  3681. }
  3682. let forceReplace = false;
  3683. if (this._destination.page >= position.first && this._destination.page <= position.page) {
  3684. if (this._destination.dest !== undefined || !this._destination.first) {
  3685. return;
  3686. }
  3687. forceReplace = true;
  3688. }
  3689. this._pushOrReplaceState(position, forceReplace);
  3690. }
  3691. _isValidPage(val) {
  3692. return Number.isInteger(val) && val > 0 && val <= this.linkService.pagesCount;
  3693. }
  3694. _isValidState(state, checkReload = false) {
  3695. if (!state) {
  3696. return false;
  3697. }
  3698. if (state.fingerprint !== this._fingerprint) {
  3699. if (checkReload) {
  3700. if (typeof state.fingerprint !== "string" || state.fingerprint.length !== this._fingerprint.length) {
  3701. return false;
  3702. }
  3703. const [perfEntry] = performance.getEntriesByType("navigation");
  3704. if (perfEntry?.type !== "reload") {
  3705. return false;
  3706. }
  3707. } else {
  3708. return false;
  3709. }
  3710. }
  3711. if (!Number.isInteger(state.uid) || state.uid < 0) {
  3712. return false;
  3713. }
  3714. if (state.destination === null || typeof state.destination !== "object") {
  3715. return false;
  3716. }
  3717. return true;
  3718. }
  3719. _updateInternalState(destination, uid, removeTemporary = false) {
  3720. if (this._updateViewareaTimeout) {
  3721. clearTimeout(this._updateViewareaTimeout);
  3722. this._updateViewareaTimeout = null;
  3723. }
  3724. if (removeTemporary && destination?.temporary) {
  3725. delete destination.temporary;
  3726. }
  3727. this._destination = destination;
  3728. this._uid = uid;
  3729. this._maxUid = Math.max(this._maxUid, uid);
  3730. this._numPositionUpdates = 0;
  3731. }
  3732. _parseCurrentHash(checkNameddest = false) {
  3733. const hash = unescape(getCurrentHash()).substring(1);
  3734. const params = (0, _ui_utils.parseQueryString)(hash);
  3735. const nameddest = params.get("nameddest") || "";
  3736. let page = params.get("page") | 0;
  3737. if (!this._isValidPage(page) || checkNameddest && nameddest.length > 0) {
  3738. page = null;
  3739. }
  3740. return {
  3741. hash,
  3742. page,
  3743. rotation: this.linkService.rotation
  3744. };
  3745. }
  3746. _updateViewarea({
  3747. location
  3748. }) {
  3749. if (this._updateViewareaTimeout) {
  3750. clearTimeout(this._updateViewareaTimeout);
  3751. this._updateViewareaTimeout = null;
  3752. }
  3753. this._position = {
  3754. hash: location.pdfOpenParams.substring(1),
  3755. page: this.linkService.page,
  3756. first: location.pageNumber,
  3757. rotation: location.rotation
  3758. };
  3759. if (this._popStateInProgress) {
  3760. return;
  3761. }
  3762. if (POSITION_UPDATED_THRESHOLD > 0 && this._isPagesLoaded && this._destination && !this._destination.page) {
  3763. this._numPositionUpdates++;
  3764. }
  3765. if (UPDATE_VIEWAREA_TIMEOUT > 0) {
  3766. this._updateViewareaTimeout = setTimeout(() => {
  3767. if (!this._popStateInProgress) {
  3768. this._tryPushCurrentPosition(true);
  3769. }
  3770. this._updateViewareaTimeout = null;
  3771. }, UPDATE_VIEWAREA_TIMEOUT);
  3772. }
  3773. }
  3774. _popState({
  3775. state
  3776. }) {
  3777. const newHash = getCurrentHash(),
  3778. hashChanged = this._currentHash !== newHash;
  3779. this._currentHash = newHash;
  3780. if (!state) {
  3781. this._uid++;
  3782. const {
  3783. hash,
  3784. page,
  3785. rotation
  3786. } = this._parseCurrentHash();
  3787. this._pushOrReplaceState({
  3788. hash,
  3789. page,
  3790. rotation
  3791. }, true);
  3792. return;
  3793. }
  3794. if (!this._isValidState(state)) {
  3795. return;
  3796. }
  3797. this._popStateInProgress = true;
  3798. if (hashChanged) {
  3799. this._blockHashChange++;
  3800. (0, _event_utils.waitOnEventOrTimeout)({
  3801. target: window,
  3802. name: "hashchange",
  3803. delay: HASH_CHANGE_TIMEOUT
  3804. }).then(() => {
  3805. this._blockHashChange--;
  3806. });
  3807. }
  3808. const destination = state.destination;
  3809. this._updateInternalState(destination, state.uid, true);
  3810. if ((0, _ui_utils.isValidRotation)(destination.rotation)) {
  3811. this.linkService.rotation = destination.rotation;
  3812. }
  3813. if (destination.dest) {
  3814. this.linkService.goToDestination(destination.dest);
  3815. } else if (destination.hash) {
  3816. this.linkService.setHash(destination.hash);
  3817. } else if (destination.page) {
  3818. this.linkService.page = destination.page;
  3819. }
  3820. Promise.resolve().then(() => {
  3821. this._popStateInProgress = false;
  3822. });
  3823. }
  3824. _pageHide() {
  3825. if (!this._destination || this._destination.temporary) {
  3826. this._tryPushCurrentPosition();
  3827. }
  3828. }
  3829. _bindEvents() {
  3830. if (this._boundEvents) {
  3831. return;
  3832. }
  3833. this._boundEvents = {
  3834. updateViewarea: this._updateViewarea.bind(this),
  3835. popState: this._popState.bind(this),
  3836. pageHide: this._pageHide.bind(this)
  3837. };
  3838. this.eventBus._on("updateviewarea", this._boundEvents.updateViewarea);
  3839. window.addEventListener("popstate", this._boundEvents.popState);
  3840. window.addEventListener("pagehide", this._boundEvents.pageHide);
  3841. }
  3842. _unbindEvents() {
  3843. if (!this._boundEvents) {
  3844. return;
  3845. }
  3846. this.eventBus._off("updateviewarea", this._boundEvents.updateViewarea);
  3847. window.removeEventListener("popstate", this._boundEvents.popState);
  3848. window.removeEventListener("pagehide", this._boundEvents.pageHide);
  3849. this._boundEvents = null;
  3850. }
  3851. }
  3852. exports.PDFHistory = PDFHistory;
  3853. function isDestHashesEqual(destHash, pushHash) {
  3854. if (typeof destHash !== "string" || typeof pushHash !== "string") {
  3855. return false;
  3856. }
  3857. if (destHash === pushHash) {
  3858. return true;
  3859. }
  3860. const nameddest = (0, _ui_utils.parseQueryString)(destHash).get("nameddest");
  3861. if (nameddest === pushHash) {
  3862. return true;
  3863. }
  3864. return false;
  3865. }
  3866. function isDestArraysEqual(firstDest, secondDest) {
  3867. function isEntryEqual(first, second) {
  3868. if (typeof first !== typeof second) {
  3869. return false;
  3870. }
  3871. if (Array.isArray(first) || Array.isArray(second)) {
  3872. return false;
  3873. }
  3874. if (first !== null && typeof first === "object" && second !== null) {
  3875. if (Object.keys(first).length !== Object.keys(second).length) {
  3876. return false;
  3877. }
  3878. for (const key in first) {
  3879. if (!isEntryEqual(first[key], second[key])) {
  3880. return false;
  3881. }
  3882. }
  3883. return true;
  3884. }
  3885. return first === second || Number.isNaN(first) && Number.isNaN(second);
  3886. }
  3887. if (!(Array.isArray(firstDest) && Array.isArray(secondDest))) {
  3888. return false;
  3889. }
  3890. if (firstDest.length !== secondDest.length) {
  3891. return false;
  3892. }
  3893. for (let i = 0, ii = firstDest.length; i < ii; i++) {
  3894. if (!isEntryEqual(firstDest[i], secondDest[i])) {
  3895. return false;
  3896. }
  3897. }
  3898. return true;
  3899. }
  3900. /***/ }),
  3901. /* 18 */
  3902. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  3903. Object.defineProperty(exports, "__esModule", ({
  3904. value: true
  3905. }));
  3906. exports.PDFPageView = void 0;
  3907. var _pdfjsLib = __w_pdfjs_require__(3);
  3908. var _ui_utils = __w_pdfjs_require__(6);
  3909. var _app_options = __w_pdfjs_require__(19);
  3910. var _l10n_utils = __w_pdfjs_require__(4);
  3911. var _text_accessibility = __w_pdfjs_require__(20);
  3912. const MAX_CANVAS_PIXELS = _app_options.compatibilityParams.maxCanvasPixels || 16777216;
  3913. class PDFPageView {
  3914. #annotationMode = _pdfjsLib.AnnotationMode.ENABLE_FORMS;
  3915. #useThumbnailCanvas = {
  3916. initialOptionalContent: true,
  3917. regularAnnotations: true
  3918. };
  3919. constructor(options) {
  3920. const container = options.container;
  3921. const defaultViewport = options.defaultViewport;
  3922. this.id = options.id;
  3923. this.renderingId = "page" + this.id;
  3924. this.pdfPage = null;
  3925. this.pageLabel = null;
  3926. this.rotation = 0;
  3927. this.scale = options.scale || _ui_utils.DEFAULT_SCALE;
  3928. this.viewport = defaultViewport;
  3929. this.pdfPageRotate = defaultViewport.rotation;
  3930. this._optionalContentConfigPromise = options.optionalContentConfigPromise || null;
  3931. this.hasRestrictedScaling = false;
  3932. this.textLayerMode = options.textLayerMode ?? _ui_utils.TextLayerMode.ENABLE;
  3933. this.#annotationMode = options.annotationMode ?? _pdfjsLib.AnnotationMode.ENABLE_FORMS;
  3934. this.imageResourcesPath = options.imageResourcesPath || "";
  3935. this.useOnlyCssZoom = options.useOnlyCssZoom || false;
  3936. this.maxCanvasPixels = options.maxCanvasPixels || MAX_CANVAS_PIXELS;
  3937. this.pageColors = options.pageColors || null;
  3938. this.eventBus = options.eventBus;
  3939. this.renderingQueue = options.renderingQueue;
  3940. this.textLayerFactory = options.textLayerFactory;
  3941. this.annotationLayerFactory = options.annotationLayerFactory;
  3942. this.annotationEditorLayerFactory = options.annotationEditorLayerFactory;
  3943. this.xfaLayerFactory = options.xfaLayerFactory;
  3944. this.textHighlighter = options.textHighlighterFactory?.createTextHighlighter({
  3945. pageIndex: this.id - 1,
  3946. eventBus: this.eventBus
  3947. });
  3948. this.structTreeLayerFactory = options.structTreeLayerFactory;
  3949. this.renderer = options.renderer || _ui_utils.RendererType.CANVAS;
  3950. this.l10n = options.l10n || _l10n_utils.NullL10n;
  3951. this.paintTask = null;
  3952. this.paintedViewportMap = new WeakMap();
  3953. this.renderingState = _ui_utils.RenderingStates.INITIAL;
  3954. this.resume = null;
  3955. this._renderError = null;
  3956. this._isStandalone = !this.renderingQueue?.hasViewer();
  3957. this._annotationCanvasMap = null;
  3958. this.annotationLayer = null;
  3959. this.annotationEditorLayer = null;
  3960. this.textLayer = null;
  3961. this.zoomLayer = null;
  3962. this.xfaLayer = null;
  3963. this.structTreeLayer = null;
  3964. const div = document.createElement("div");
  3965. div.className = "page";
  3966. div.style.width = Math.floor(this.viewport.width) + "px";
  3967. div.style.height = Math.floor(this.viewport.height) + "px";
  3968. div.setAttribute("data-page-number", this.id);
  3969. div.setAttribute("role", "region");
  3970. this.l10n.get("page_landmark", {
  3971. page: this.id
  3972. }).then(msg => {
  3973. div.setAttribute("aria-label", msg);
  3974. });
  3975. this.div = div;
  3976. container?.append(div);
  3977. if (this._isStandalone) {
  3978. const {
  3979. optionalContentConfigPromise
  3980. } = options;
  3981. if (optionalContentConfigPromise) {
  3982. optionalContentConfigPromise.then(optionalContentConfig => {
  3983. if (optionalContentConfigPromise !== this._optionalContentConfigPromise) {
  3984. return;
  3985. }
  3986. this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility;
  3987. });
  3988. }
  3989. }
  3990. }
  3991. setPdfPage(pdfPage) {
  3992. this.pdfPage = pdfPage;
  3993. this.pdfPageRotate = pdfPage.rotate;
  3994. const totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  3995. this.viewport = pdfPage.getViewport({
  3996. scale: this.scale * _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS,
  3997. rotation: totalRotation
  3998. });
  3999. this.reset();
  4000. }
  4001. destroy() {
  4002. this.reset();
  4003. this.pdfPage?.cleanup();
  4004. }
  4005. async _renderAnnotationLayer() {
  4006. let error = null;
  4007. try {
  4008. await this.annotationLayer.render(this.viewport, "display");
  4009. } catch (ex) {
  4010. console.error(`_renderAnnotationLayer: "${ex}".`);
  4011. error = ex;
  4012. } finally {
  4013. this.eventBus.dispatch("annotationlayerrendered", {
  4014. source: this,
  4015. pageNumber: this.id,
  4016. error
  4017. });
  4018. }
  4019. }
  4020. async _renderAnnotationEditorLayer() {
  4021. let error = null;
  4022. try {
  4023. await this.annotationEditorLayer.render(this.viewport, "display");
  4024. } catch (ex) {
  4025. console.error(`_renderAnnotationEditorLayer: "${ex}".`);
  4026. error = ex;
  4027. } finally {
  4028. this.eventBus.dispatch("annotationeditorlayerrendered", {
  4029. source: this,
  4030. pageNumber: this.id,
  4031. error
  4032. });
  4033. }
  4034. }
  4035. async _renderXfaLayer() {
  4036. let error = null;
  4037. try {
  4038. const result = await this.xfaLayer.render(this.viewport, "display");
  4039. if (result?.textDivs && this.textHighlighter) {
  4040. this._buildXfaTextContentItems(result.textDivs);
  4041. }
  4042. } catch (ex) {
  4043. console.error(`_renderXfaLayer: "${ex}".`);
  4044. error = ex;
  4045. } finally {
  4046. this.eventBus.dispatch("xfalayerrendered", {
  4047. source: this,
  4048. pageNumber: this.id,
  4049. error
  4050. });
  4051. }
  4052. }
  4053. async _buildXfaTextContentItems(textDivs) {
  4054. const text = await this.pdfPage.getTextContent();
  4055. const items = [];
  4056. for (const item of text.items) {
  4057. items.push(item.str);
  4058. }
  4059. this.textHighlighter.setTextMapping(textDivs, items);
  4060. this.textHighlighter.enable();
  4061. }
  4062. _resetZoomLayer(removeFromDOM = false) {
  4063. if (!this.zoomLayer) {
  4064. return;
  4065. }
  4066. const zoomLayerCanvas = this.zoomLayer.firstChild;
  4067. this.paintedViewportMap.delete(zoomLayerCanvas);
  4068. zoomLayerCanvas.width = 0;
  4069. zoomLayerCanvas.height = 0;
  4070. if (removeFromDOM) {
  4071. this.zoomLayer.remove();
  4072. }
  4073. this.zoomLayer = null;
  4074. }
  4075. reset({
  4076. keepZoomLayer = false,
  4077. keepAnnotationLayer = false,
  4078. keepAnnotationEditorLayer = false,
  4079. keepXfaLayer = false
  4080. } = {}) {
  4081. this.cancelRendering({
  4082. keepAnnotationLayer,
  4083. keepAnnotationEditorLayer,
  4084. keepXfaLayer
  4085. });
  4086. this.renderingState = _ui_utils.RenderingStates.INITIAL;
  4087. const div = this.div;
  4088. div.style.width = Math.floor(this.viewport.width) + "px";
  4089. div.style.height = Math.floor(this.viewport.height) + "px";
  4090. const childNodes = div.childNodes,
  4091. zoomLayerNode = keepZoomLayer && this.zoomLayer || null,
  4092. annotationLayerNode = keepAnnotationLayer && this.annotationLayer?.div || null,
  4093. annotationEditorLayerNode = keepAnnotationEditorLayer && this.annotationEditorLayer?.div || null,
  4094. xfaLayerNode = keepXfaLayer && this.xfaLayer?.div || null;
  4095. for (let i = childNodes.length - 1; i >= 0; i--) {
  4096. const node = childNodes[i];
  4097. switch (node) {
  4098. case zoomLayerNode:
  4099. case annotationLayerNode:
  4100. case annotationEditorLayerNode:
  4101. case xfaLayerNode:
  4102. continue;
  4103. }
  4104. node.remove();
  4105. }
  4106. div.removeAttribute("data-loaded");
  4107. if (annotationLayerNode) {
  4108. this.annotationLayer.hide();
  4109. }
  4110. if (annotationEditorLayerNode) {
  4111. this.annotationEditorLayer.hide();
  4112. } else {
  4113. this.annotationEditorLayer?.destroy();
  4114. }
  4115. if (xfaLayerNode) {
  4116. this.xfaLayer.hide();
  4117. }
  4118. if (!zoomLayerNode) {
  4119. if (this.canvas) {
  4120. this.paintedViewportMap.delete(this.canvas);
  4121. this.canvas.width = 0;
  4122. this.canvas.height = 0;
  4123. delete this.canvas;
  4124. }
  4125. this._resetZoomLayer();
  4126. }
  4127. if (this.svg) {
  4128. this.paintedViewportMap.delete(this.svg);
  4129. delete this.svg;
  4130. }
  4131. this.loadingIconDiv = document.createElement("div");
  4132. this.loadingIconDiv.className = "loadingIcon notVisible";
  4133. if (this._isStandalone) {
  4134. this.toggleLoadingIconSpinner(true);
  4135. }
  4136. this.loadingIconDiv.setAttribute("role", "img");
  4137. this.l10n.get("loading").then(msg => {
  4138. this.loadingIconDiv?.setAttribute("aria-label", msg);
  4139. });
  4140. div.append(this.loadingIconDiv);
  4141. }
  4142. update({
  4143. scale = 0,
  4144. rotation = null,
  4145. optionalContentConfigPromise = null
  4146. }) {
  4147. this.scale = scale || this.scale;
  4148. if (typeof rotation === "number") {
  4149. this.rotation = rotation;
  4150. }
  4151. if (optionalContentConfigPromise instanceof Promise) {
  4152. this._optionalContentConfigPromise = optionalContentConfigPromise;
  4153. optionalContentConfigPromise.then(optionalContentConfig => {
  4154. if (optionalContentConfigPromise !== this._optionalContentConfigPromise) {
  4155. return;
  4156. }
  4157. this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility;
  4158. });
  4159. }
  4160. const totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  4161. this.viewport = this.viewport.clone({
  4162. scale: this.scale * _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS,
  4163. rotation: totalRotation
  4164. });
  4165. if (this._isStandalone) {
  4166. _ui_utils.docStyle.setProperty("--scale-factor", this.viewport.scale);
  4167. }
  4168. if (this.svg) {
  4169. this.cssTransform({
  4170. target: this.svg,
  4171. redrawAnnotationLayer: true,
  4172. redrawAnnotationEditorLayer: true,
  4173. redrawXfaLayer: true
  4174. });
  4175. this.eventBus.dispatch("pagerendered", {
  4176. source: this,
  4177. pageNumber: this.id,
  4178. cssTransform: true,
  4179. timestamp: performance.now(),
  4180. error: this._renderError
  4181. });
  4182. return;
  4183. }
  4184. let isScalingRestricted = false;
  4185. if (this.canvas && this.maxCanvasPixels > 0) {
  4186. const outputScale = this.outputScale;
  4187. if ((Math.floor(this.viewport.width) * outputScale.sx | 0) * (Math.floor(this.viewport.height) * outputScale.sy | 0) > this.maxCanvasPixels) {
  4188. isScalingRestricted = true;
  4189. }
  4190. }
  4191. if (this.canvas) {
  4192. if (this.useOnlyCssZoom || this.hasRestrictedScaling && isScalingRestricted) {
  4193. this.cssTransform({
  4194. target: this.canvas,
  4195. redrawAnnotationLayer: true,
  4196. redrawAnnotationEditorLayer: true,
  4197. redrawXfaLayer: true
  4198. });
  4199. this.eventBus.dispatch("pagerendered", {
  4200. source: this,
  4201. pageNumber: this.id,
  4202. cssTransform: true,
  4203. timestamp: performance.now(),
  4204. error: this._renderError
  4205. });
  4206. return;
  4207. }
  4208. if (!this.zoomLayer && !this.canvas.hidden) {
  4209. this.zoomLayer = this.canvas.parentNode;
  4210. this.zoomLayer.style.position = "absolute";
  4211. }
  4212. }
  4213. if (this.zoomLayer) {
  4214. this.cssTransform({
  4215. target: this.zoomLayer.firstChild
  4216. });
  4217. }
  4218. this.reset({
  4219. keepZoomLayer: true,
  4220. keepAnnotationLayer: true,
  4221. keepAnnotationEditorLayer: true,
  4222. keepXfaLayer: true
  4223. });
  4224. }
  4225. cancelRendering({
  4226. keepAnnotationLayer = false,
  4227. keepAnnotationEditorLayer = false,
  4228. keepXfaLayer = false
  4229. } = {}) {
  4230. if (this.paintTask) {
  4231. this.paintTask.cancel();
  4232. this.paintTask = null;
  4233. }
  4234. this.resume = null;
  4235. if (this.textLayer) {
  4236. this.textLayer.cancel();
  4237. this.textLayer = null;
  4238. }
  4239. if (this.annotationLayer && (!keepAnnotationLayer || !this.annotationLayer.div)) {
  4240. this.annotationLayer.cancel();
  4241. this.annotationLayer = null;
  4242. this._annotationCanvasMap = null;
  4243. }
  4244. if (this.annotationEditorLayer && (!keepAnnotationEditorLayer || !this.annotationEditorLayer.div)) {
  4245. this.annotationEditorLayer.cancel();
  4246. this.annotationEditorLayer = null;
  4247. }
  4248. if (this.xfaLayer && (!keepXfaLayer || !this.xfaLayer.div)) {
  4249. this.xfaLayer.cancel();
  4250. this.xfaLayer = null;
  4251. this.textHighlighter?.disable();
  4252. }
  4253. if (this._onTextLayerRendered) {
  4254. this.eventBus._off("textlayerrendered", this._onTextLayerRendered);
  4255. this._onTextLayerRendered = null;
  4256. }
  4257. }
  4258. cssTransform({
  4259. target,
  4260. redrawAnnotationLayer = false,
  4261. redrawAnnotationEditorLayer = false,
  4262. redrawXfaLayer = false
  4263. }) {
  4264. const width = this.viewport.width;
  4265. const height = this.viewport.height;
  4266. const div = this.div;
  4267. target.style.width = target.parentNode.style.width = div.style.width = Math.floor(width) + "px";
  4268. target.style.height = target.parentNode.style.height = div.style.height = Math.floor(height) + "px";
  4269. const relativeRotation = this.viewport.rotation - this.paintedViewportMap.get(target).rotation;
  4270. const absRotation = Math.abs(relativeRotation);
  4271. let scaleX = 1,
  4272. scaleY = 1;
  4273. if (absRotation === 90 || absRotation === 270) {
  4274. scaleX = height / width;
  4275. scaleY = width / height;
  4276. }
  4277. target.style.transform = `rotate(${relativeRotation}deg) scale(${scaleX}, ${scaleY})`;
  4278. if (this.textLayer) {
  4279. const textLayerViewport = this.textLayer.viewport;
  4280. const textRelativeRotation = this.viewport.rotation - textLayerViewport.rotation;
  4281. const textAbsRotation = Math.abs(textRelativeRotation);
  4282. let scale = width / textLayerViewport.width;
  4283. if (textAbsRotation === 90 || textAbsRotation === 270) {
  4284. scale = width / textLayerViewport.height;
  4285. }
  4286. const textLayerDiv = this.textLayer.textLayerDiv;
  4287. let transX, transY;
  4288. switch (textAbsRotation) {
  4289. case 0:
  4290. transX = transY = 0;
  4291. break;
  4292. case 90:
  4293. transX = 0;
  4294. transY = "-" + textLayerDiv.style.height;
  4295. break;
  4296. case 180:
  4297. transX = "-" + textLayerDiv.style.width;
  4298. transY = "-" + textLayerDiv.style.height;
  4299. break;
  4300. case 270:
  4301. transX = "-" + textLayerDiv.style.width;
  4302. transY = 0;
  4303. break;
  4304. default:
  4305. console.error("Bad rotation value.");
  4306. break;
  4307. }
  4308. textLayerDiv.style.transform = `rotate(${textAbsRotation}deg) ` + `scale(${scale}) ` + `translate(${transX}, ${transY})`;
  4309. textLayerDiv.style.transformOrigin = "0% 0%";
  4310. }
  4311. if (redrawAnnotationLayer && this.annotationLayer) {
  4312. this._renderAnnotationLayer();
  4313. }
  4314. if (redrawAnnotationEditorLayer && this.annotationEditorLayer) {
  4315. this._renderAnnotationEditorLayer();
  4316. }
  4317. if (redrawXfaLayer && this.xfaLayer) {
  4318. this._renderXfaLayer();
  4319. }
  4320. }
  4321. get width() {
  4322. return this.viewport.width;
  4323. }
  4324. get height() {
  4325. return this.viewport.height;
  4326. }
  4327. getPagePoint(x, y) {
  4328. return this.viewport.convertToPdfPoint(x, y);
  4329. }
  4330. toggleLoadingIconSpinner(viewVisible = false) {
  4331. this.loadingIconDiv?.classList.toggle("notVisible", !viewVisible);
  4332. }
  4333. draw() {
  4334. if (this.renderingState !== _ui_utils.RenderingStates.INITIAL) {
  4335. console.error("Must be in new state before drawing");
  4336. this.reset();
  4337. }
  4338. const {
  4339. div,
  4340. pdfPage
  4341. } = this;
  4342. if (!pdfPage) {
  4343. this.renderingState = _ui_utils.RenderingStates.FINISHED;
  4344. if (this.loadingIconDiv) {
  4345. this.loadingIconDiv.remove();
  4346. delete this.loadingIconDiv;
  4347. }
  4348. return Promise.reject(new Error("pdfPage is not loaded"));
  4349. }
  4350. this.renderingState = _ui_utils.RenderingStates.RUNNING;
  4351. const canvasWrapper = document.createElement("div");
  4352. canvasWrapper.style.width = div.style.width;
  4353. canvasWrapper.style.height = div.style.height;
  4354. canvasWrapper.classList.add("canvasWrapper");
  4355. const lastDivBeforeTextDiv = this.annotationLayer?.div || this.annotationEditorLayer?.div;
  4356. if (lastDivBeforeTextDiv) {
  4357. lastDivBeforeTextDiv.before(canvasWrapper);
  4358. } else {
  4359. div.append(canvasWrapper);
  4360. }
  4361. let textLayer = null;
  4362. if (this.textLayerMode !== _ui_utils.TextLayerMode.DISABLE && this.textLayerFactory) {
  4363. this._accessibilityManager ||= new _text_accessibility.TextAccessibilityManager();
  4364. const textLayerDiv = document.createElement("div");
  4365. textLayerDiv.className = "textLayer";
  4366. textLayerDiv.style.width = canvasWrapper.style.width;
  4367. textLayerDiv.style.height = canvasWrapper.style.height;
  4368. if (lastDivBeforeTextDiv) {
  4369. lastDivBeforeTextDiv.before(textLayerDiv);
  4370. } else {
  4371. div.append(textLayerDiv);
  4372. }
  4373. textLayer = this.textLayerFactory.createTextLayerBuilder({
  4374. textLayerDiv,
  4375. pageIndex: this.id - 1,
  4376. viewport: this.viewport,
  4377. eventBus: this.eventBus,
  4378. highlighter: this.textHighlighter,
  4379. accessibilityManager: this._accessibilityManager
  4380. });
  4381. }
  4382. this.textLayer = textLayer;
  4383. if (this.#annotationMode !== _pdfjsLib.AnnotationMode.DISABLE && this.annotationLayerFactory) {
  4384. this._annotationCanvasMap ||= new Map();
  4385. this.annotationLayer ||= this.annotationLayerFactory.createAnnotationLayerBuilder({
  4386. pageDiv: div,
  4387. pdfPage,
  4388. imageResourcesPath: this.imageResourcesPath,
  4389. renderForms: this.#annotationMode === _pdfjsLib.AnnotationMode.ENABLE_FORMS,
  4390. l10n: this.l10n,
  4391. annotationCanvasMap: this._annotationCanvasMap,
  4392. accessibilityManager: this._accessibilityManager
  4393. });
  4394. }
  4395. if (this.xfaLayer?.div) {
  4396. div.append(this.xfaLayer.div);
  4397. }
  4398. let renderContinueCallback = null;
  4399. if (this.renderingQueue) {
  4400. renderContinueCallback = cont => {
  4401. if (!this.renderingQueue.isHighestPriority(this)) {
  4402. this.renderingState = _ui_utils.RenderingStates.PAUSED;
  4403. this.resume = () => {
  4404. this.renderingState = _ui_utils.RenderingStates.RUNNING;
  4405. cont();
  4406. };
  4407. return;
  4408. }
  4409. cont();
  4410. };
  4411. }
  4412. const finishPaintTask = async (error = null) => {
  4413. if (paintTask === this.paintTask) {
  4414. this.paintTask = null;
  4415. }
  4416. if (error instanceof _pdfjsLib.RenderingCancelledException) {
  4417. this._renderError = null;
  4418. return;
  4419. }
  4420. this._renderError = error;
  4421. this.renderingState = _ui_utils.RenderingStates.FINISHED;
  4422. if (this.loadingIconDiv) {
  4423. this.loadingIconDiv.remove();
  4424. delete this.loadingIconDiv;
  4425. }
  4426. this._resetZoomLayer(true);
  4427. this.#useThumbnailCanvas.regularAnnotations = !paintTask.separateAnnots;
  4428. this.eventBus.dispatch("pagerendered", {
  4429. source: this,
  4430. pageNumber: this.id,
  4431. cssTransform: false,
  4432. timestamp: performance.now(),
  4433. error: this._renderError
  4434. });
  4435. if (error) {
  4436. throw error;
  4437. }
  4438. };
  4439. const paintTask = this.renderer === _ui_utils.RendererType.SVG ? this.paintOnSvg(canvasWrapper) : this.paintOnCanvas(canvasWrapper);
  4440. paintTask.onRenderContinue = renderContinueCallback;
  4441. this.paintTask = paintTask;
  4442. const resultPromise = paintTask.promise.then(() => {
  4443. return finishPaintTask(null).then(() => {
  4444. if (textLayer) {
  4445. const readableStream = pdfPage.streamTextContent({
  4446. includeMarkedContent: true
  4447. });
  4448. textLayer.setTextContentStream(readableStream);
  4449. textLayer.render();
  4450. }
  4451. if (this.annotationLayer) {
  4452. this._renderAnnotationLayer().then(() => {
  4453. if (this.annotationEditorLayerFactory) {
  4454. this.annotationEditorLayer ||= this.annotationEditorLayerFactory.createAnnotationEditorLayerBuilder({
  4455. pageDiv: div,
  4456. pdfPage,
  4457. l10n: this.l10n,
  4458. accessibilityManager: this._accessibilityManager
  4459. });
  4460. this._renderAnnotationEditorLayer();
  4461. }
  4462. });
  4463. }
  4464. });
  4465. }, function (reason) {
  4466. return finishPaintTask(reason);
  4467. });
  4468. if (this.xfaLayerFactory) {
  4469. this.xfaLayer ||= this.xfaLayerFactory.createXfaLayerBuilder({
  4470. pageDiv: div,
  4471. pdfPage
  4472. });
  4473. this._renderXfaLayer();
  4474. }
  4475. if (this.structTreeLayerFactory && this.textLayer && this.canvas) {
  4476. this._onTextLayerRendered = event => {
  4477. if (event.pageNumber !== this.id) {
  4478. return;
  4479. }
  4480. this.eventBus._off("textlayerrendered", this._onTextLayerRendered);
  4481. this._onTextLayerRendered = null;
  4482. if (!this.canvas) {
  4483. return;
  4484. }
  4485. this.pdfPage.getStructTree().then(tree => {
  4486. if (!tree) {
  4487. return;
  4488. }
  4489. if (!this.canvas) {
  4490. return;
  4491. }
  4492. const treeDom = this.structTreeLayer.render(tree);
  4493. treeDom.classList.add("structTree");
  4494. this.canvas.append(treeDom);
  4495. });
  4496. };
  4497. this.eventBus._on("textlayerrendered", this._onTextLayerRendered);
  4498. this.structTreeLayer = this.structTreeLayerFactory.createStructTreeLayerBuilder({
  4499. pdfPage
  4500. });
  4501. }
  4502. div.setAttribute("data-loaded", true);
  4503. this.eventBus.dispatch("pagerender", {
  4504. source: this,
  4505. pageNumber: this.id
  4506. });
  4507. return resultPromise;
  4508. }
  4509. paintOnCanvas(canvasWrapper) {
  4510. const renderCapability = (0, _pdfjsLib.createPromiseCapability)();
  4511. const result = {
  4512. promise: renderCapability.promise,
  4513. onRenderContinue(cont) {
  4514. cont();
  4515. },
  4516. cancel() {
  4517. renderTask.cancel();
  4518. },
  4519. get separateAnnots() {
  4520. return renderTask.separateAnnots;
  4521. }
  4522. };
  4523. const viewport = this.viewport;
  4524. const canvas = document.createElement("canvas");
  4525. canvas.setAttribute("role", "presentation");
  4526. canvas.hidden = true;
  4527. let isCanvasHidden = true;
  4528. const showCanvas = function () {
  4529. if (isCanvasHidden) {
  4530. canvas.hidden = false;
  4531. isCanvasHidden = false;
  4532. }
  4533. };
  4534. canvasWrapper.append(canvas);
  4535. this.canvas = canvas;
  4536. const ctx = canvas.getContext("2d", {
  4537. alpha: false
  4538. });
  4539. const outputScale = this.outputScale = new _ui_utils.OutputScale();
  4540. if (this.useOnlyCssZoom) {
  4541. const actualSizeViewport = viewport.clone({
  4542. scale: _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS
  4543. });
  4544. outputScale.sx *= actualSizeViewport.width / viewport.width;
  4545. outputScale.sy *= actualSizeViewport.height / viewport.height;
  4546. }
  4547. if (this.maxCanvasPixels > 0) {
  4548. const pixelsInViewport = viewport.width * viewport.height;
  4549. const maxScale = Math.sqrt(this.maxCanvasPixels / pixelsInViewport);
  4550. if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
  4551. outputScale.sx = maxScale;
  4552. outputScale.sy = maxScale;
  4553. this.hasRestrictedScaling = true;
  4554. } else {
  4555. this.hasRestrictedScaling = false;
  4556. }
  4557. }
  4558. const sfx = (0, _ui_utils.approximateFraction)(outputScale.sx);
  4559. const sfy = (0, _ui_utils.approximateFraction)(outputScale.sy);
  4560. canvas.width = (0, _ui_utils.roundToDivide)(viewport.width * outputScale.sx, sfx[0]);
  4561. canvas.height = (0, _ui_utils.roundToDivide)(viewport.height * outputScale.sy, sfy[0]);
  4562. canvas.style.width = (0, _ui_utils.roundToDivide)(viewport.width, sfx[1]) + "px";
  4563. canvas.style.height = (0, _ui_utils.roundToDivide)(viewport.height, sfy[1]) + "px";
  4564. this.paintedViewportMap.set(canvas, viewport);
  4565. const transform = outputScale.scaled ? [outputScale.sx, 0, 0, outputScale.sy, 0, 0] : null;
  4566. const renderContext = {
  4567. canvasContext: ctx,
  4568. transform,
  4569. viewport: this.viewport,
  4570. annotationMode: this.#annotationMode,
  4571. optionalContentConfigPromise: this._optionalContentConfigPromise,
  4572. annotationCanvasMap: this._annotationCanvasMap,
  4573. pageColors: this.pageColors
  4574. };
  4575. const renderTask = this.pdfPage.render(renderContext);
  4576. renderTask.onContinue = function (cont) {
  4577. showCanvas();
  4578. if (result.onRenderContinue) {
  4579. result.onRenderContinue(cont);
  4580. } else {
  4581. cont();
  4582. }
  4583. };
  4584. renderTask.promise.then(function () {
  4585. showCanvas();
  4586. renderCapability.resolve();
  4587. }, function (error) {
  4588. showCanvas();
  4589. renderCapability.reject(error);
  4590. });
  4591. return result;
  4592. }
  4593. paintOnSvg(wrapper) {
  4594. let cancelled = false;
  4595. const ensureNotCancelled = () => {
  4596. if (cancelled) {
  4597. throw new _pdfjsLib.RenderingCancelledException(`Rendering cancelled, page ${this.id}`, "svg");
  4598. }
  4599. };
  4600. const pdfPage = this.pdfPage;
  4601. const actualSizeViewport = this.viewport.clone({
  4602. scale: _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS
  4603. });
  4604. const promise = pdfPage.getOperatorList({
  4605. annotationMode: this.#annotationMode
  4606. }).then(opList => {
  4607. ensureNotCancelled();
  4608. const svgGfx = new _pdfjsLib.SVGGraphics(pdfPage.commonObjs, pdfPage.objs);
  4609. return svgGfx.getSVG(opList, actualSizeViewport).then(svg => {
  4610. ensureNotCancelled();
  4611. this.svg = svg;
  4612. this.paintedViewportMap.set(svg, actualSizeViewport);
  4613. svg.style.width = wrapper.style.width;
  4614. svg.style.height = wrapper.style.height;
  4615. this.renderingState = _ui_utils.RenderingStates.FINISHED;
  4616. wrapper.append(svg);
  4617. });
  4618. });
  4619. return {
  4620. promise,
  4621. onRenderContinue(cont) {
  4622. cont();
  4623. },
  4624. cancel() {
  4625. cancelled = true;
  4626. },
  4627. get separateAnnots() {
  4628. return false;
  4629. }
  4630. };
  4631. }
  4632. setPageLabel(label) {
  4633. this.pageLabel = typeof label === "string" ? label : null;
  4634. if (this.pageLabel !== null) {
  4635. this.div.setAttribute("data-page-label", this.pageLabel);
  4636. } else {
  4637. this.div.removeAttribute("data-page-label");
  4638. }
  4639. }
  4640. get thumbnailCanvas() {
  4641. const {
  4642. initialOptionalContent,
  4643. regularAnnotations
  4644. } = this.#useThumbnailCanvas;
  4645. return initialOptionalContent && regularAnnotations ? this.canvas : null;
  4646. }
  4647. }
  4648. exports.PDFPageView = PDFPageView;
  4649. /***/ }),
  4650. /* 19 */
  4651. /***/ ((__unused_webpack_module, exports) => {
  4652. Object.defineProperty(exports, "__esModule", ({
  4653. value: true
  4654. }));
  4655. exports.compatibilityParams = exports.OptionKind = exports.AppOptions = void 0;
  4656. const compatibilityParams = Object.create(null);
  4657. exports.compatibilityParams = compatibilityParams;
  4658. {
  4659. const userAgent = navigator.userAgent || "";
  4660. const platform = navigator.platform || "";
  4661. const maxTouchPoints = navigator.maxTouchPoints || 1;
  4662. const isAndroid = /Android/.test(userAgent);
  4663. const isIOS = /\b(iPad|iPhone|iPod)(?=;)/.test(userAgent) || platform === "MacIntel" && maxTouchPoints > 1;
  4664. (function checkCanvasSizeLimitation() {
  4665. if (isIOS || isAndroid) {
  4666. compatibilityParams.maxCanvasPixels = 5242880;
  4667. }
  4668. })();
  4669. }
  4670. const OptionKind = {
  4671. VIEWER: 0x02,
  4672. API: 0x04,
  4673. WORKER: 0x08,
  4674. PREFERENCE: 0x80
  4675. };
  4676. exports.OptionKind = OptionKind;
  4677. const defaultOptions = {
  4678. annotationEditorMode: {
  4679. value: 0,
  4680. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  4681. },
  4682. annotationMode: {
  4683. value: 2,
  4684. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  4685. },
  4686. cursorToolOnLoad: {
  4687. value: 0,
  4688. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  4689. },
  4690. defaultZoomValue: {
  4691. value: "",
  4692. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  4693. },
  4694. disableHistory: {
  4695. value: false,
  4696. kind: OptionKind.VIEWER
  4697. },
  4698. disablePageLabels: {
  4699. value: false,
  4700. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  4701. },
  4702. enablePermissions: {
  4703. value: false,
  4704. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  4705. },
  4706. enablePrintAutoRotate: {
  4707. value: true,
  4708. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  4709. },
  4710. enableScripting: {
  4711. value: true,
  4712. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  4713. },
  4714. externalLinkRel: {
  4715. value: "noopener noreferrer nofollow",
  4716. kind: OptionKind.VIEWER
  4717. },
  4718. externalLinkTarget: {
  4719. value: 0,
  4720. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  4721. },
  4722. historyUpdateUrl: {
  4723. value: false,
  4724. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  4725. },
  4726. ignoreDestinationZoom: {
  4727. value: false,
  4728. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  4729. },
  4730. imageResourcesPath: {
  4731. value: "./images/",
  4732. kind: OptionKind.VIEWER
  4733. },
  4734. maxCanvasPixels: {
  4735. value: 16777216,
  4736. kind: OptionKind.VIEWER
  4737. },
  4738. forcePageColors: {
  4739. value: false,
  4740. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  4741. },
  4742. pageColorsBackground: {
  4743. value: "Canvas",
  4744. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  4745. },
  4746. pageColorsForeground: {
  4747. value: "CanvasText",
  4748. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  4749. },
  4750. pdfBugEnabled: {
  4751. value: false,
  4752. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  4753. },
  4754. printResolution: {
  4755. value: 150,
  4756. kind: OptionKind.VIEWER
  4757. },
  4758. sidebarViewOnLoad: {
  4759. value: -1,
  4760. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  4761. },
  4762. scrollModeOnLoad: {
  4763. value: -1,
  4764. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  4765. },
  4766. spreadModeOnLoad: {
  4767. value: -1,
  4768. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  4769. },
  4770. textLayerMode: {
  4771. value: 1,
  4772. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  4773. },
  4774. useOnlyCssZoom: {
  4775. value: false,
  4776. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  4777. },
  4778. viewerCssTheme: {
  4779. value: 0,
  4780. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  4781. },
  4782. viewOnLoad: {
  4783. value: 0,
  4784. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  4785. },
  4786. cMapPacked: {
  4787. value: true,
  4788. kind: OptionKind.API
  4789. },
  4790. cMapUrl: {
  4791. value: "../web/cmaps/",
  4792. kind: OptionKind.API
  4793. },
  4794. disableAutoFetch: {
  4795. value: false,
  4796. kind: OptionKind.API + OptionKind.PREFERENCE
  4797. },
  4798. disableFontFace: {
  4799. value: false,
  4800. kind: OptionKind.API + OptionKind.PREFERENCE
  4801. },
  4802. disableRange: {
  4803. value: false,
  4804. kind: OptionKind.API + OptionKind.PREFERENCE
  4805. },
  4806. disableStream: {
  4807. value: false,
  4808. kind: OptionKind.API + OptionKind.PREFERENCE
  4809. },
  4810. docBaseUrl: {
  4811. value: "",
  4812. kind: OptionKind.API
  4813. },
  4814. enableXfa: {
  4815. value: true,
  4816. kind: OptionKind.API + OptionKind.PREFERENCE
  4817. },
  4818. fontExtraProperties: {
  4819. value: false,
  4820. kind: OptionKind.API
  4821. },
  4822. isEvalSupported: {
  4823. value: true,
  4824. kind: OptionKind.API
  4825. },
  4826. isOffscreenCanvasSupported: {
  4827. value: true,
  4828. kind: OptionKind.API
  4829. },
  4830. maxImageSize: {
  4831. value: -1,
  4832. kind: OptionKind.API
  4833. },
  4834. pdfBug: {
  4835. value: false,
  4836. kind: OptionKind.API
  4837. },
  4838. standardFontDataUrl: {
  4839. value: "../web/standard_fonts/",
  4840. kind: OptionKind.API
  4841. },
  4842. verbosity: {
  4843. value: 1,
  4844. kind: OptionKind.API
  4845. },
  4846. workerPort: {
  4847. value: null,
  4848. kind: OptionKind.WORKER
  4849. },
  4850. workerSrc: {
  4851. value: "../build/pdf.worker.js",
  4852. kind: OptionKind.WORKER
  4853. }
  4854. };
  4855. {
  4856. defaultOptions.defaultUrl = {
  4857. value: "compressed.tracemonkey-pldi-09.pdf",
  4858. kind: OptionKind.VIEWER
  4859. };
  4860. defaultOptions.disablePreferences = {
  4861. value: false,
  4862. kind: OptionKind.VIEWER
  4863. };
  4864. defaultOptions.locale = {
  4865. value: navigator.language || "en-US",
  4866. kind: OptionKind.VIEWER
  4867. };
  4868. defaultOptions.renderer = {
  4869. value: "canvas",
  4870. kind: OptionKind.VIEWER + OptionKind.PREFERENCE
  4871. };
  4872. defaultOptions.sandboxBundleSrc = {
  4873. value: "../build/pdf.sandbox.js",
  4874. kind: OptionKind.VIEWER
  4875. };
  4876. }
  4877. const userOptions = Object.create(null);
  4878. class AppOptions {
  4879. constructor() {
  4880. throw new Error("Cannot initialize AppOptions.");
  4881. }
  4882. static get(name) {
  4883. const userOption = userOptions[name];
  4884. if (userOption !== undefined) {
  4885. return userOption;
  4886. }
  4887. const defaultOption = defaultOptions[name];
  4888. if (defaultOption !== undefined) {
  4889. return compatibilityParams[name] ?? defaultOption.value;
  4890. }
  4891. return undefined;
  4892. }
  4893. static getAll(kind = null) {
  4894. const options = Object.create(null);
  4895. for (const name in defaultOptions) {
  4896. const defaultOption = defaultOptions[name];
  4897. if (kind) {
  4898. if ((kind & defaultOption.kind) === 0) {
  4899. continue;
  4900. }
  4901. if (kind === OptionKind.PREFERENCE) {
  4902. const value = defaultOption.value,
  4903. valueType = typeof value;
  4904. if (valueType === "boolean" || valueType === "string" || valueType === "number" && Number.isInteger(value)) {
  4905. options[name] = value;
  4906. continue;
  4907. }
  4908. throw new Error(`Invalid type for preference: ${name}`);
  4909. }
  4910. }
  4911. const userOption = userOptions[name];
  4912. options[name] = userOption !== undefined ? userOption : compatibilityParams[name] ?? defaultOption.value;
  4913. }
  4914. return options;
  4915. }
  4916. static set(name, value) {
  4917. userOptions[name] = value;
  4918. }
  4919. static setAll(options) {
  4920. for (const name in options) {
  4921. userOptions[name] = options[name];
  4922. }
  4923. }
  4924. static remove(name) {
  4925. delete userOptions[name];
  4926. }
  4927. static _hasUserOptions() {
  4928. return Object.keys(userOptions).length > 0;
  4929. }
  4930. }
  4931. exports.AppOptions = AppOptions;
  4932. /***/ }),
  4933. /* 20 */
  4934. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  4935. Object.defineProperty(exports, "__esModule", ({
  4936. value: true
  4937. }));
  4938. exports.TextAccessibilityManager = void 0;
  4939. var _ui_utils = __w_pdfjs_require__(6);
  4940. class TextAccessibilityManager {
  4941. #enabled = false;
  4942. #textChildren = null;
  4943. #textNodes = new Map();
  4944. #waitingElements = new Map();
  4945. setTextMapping(textDivs) {
  4946. this.#textChildren = textDivs;
  4947. }
  4948. static #compareElementPositions(e1, e2) {
  4949. const rect1 = e1.getBoundingClientRect();
  4950. const rect2 = e2.getBoundingClientRect();
  4951. if (rect1.width === 0 && rect1.height === 0) {
  4952. return +1;
  4953. }
  4954. if (rect2.width === 0 && rect2.height === 0) {
  4955. return -1;
  4956. }
  4957. const top1 = rect1.y;
  4958. const bot1 = rect1.y + rect1.height;
  4959. const mid1 = rect1.y + rect1.height / 2;
  4960. const top2 = rect2.y;
  4961. const bot2 = rect2.y + rect2.height;
  4962. const mid2 = rect2.y + rect2.height / 2;
  4963. if (mid1 <= top2 && mid2 >= bot1) {
  4964. return -1;
  4965. }
  4966. if (mid2 <= top1 && mid1 >= bot2) {
  4967. return +1;
  4968. }
  4969. const centerX1 = rect1.x + rect1.width / 2;
  4970. const centerX2 = rect2.x + rect2.width / 2;
  4971. return centerX1 - centerX2;
  4972. }
  4973. enable() {
  4974. if (this.#enabled) {
  4975. throw new Error("TextAccessibilityManager is already enabled.");
  4976. }
  4977. if (!this.#textChildren) {
  4978. throw new Error("Text divs and strings have not been set.");
  4979. }
  4980. this.#enabled = true;
  4981. this.#textChildren = this.#textChildren.slice();
  4982. this.#textChildren.sort(TextAccessibilityManager.#compareElementPositions);
  4983. if (this.#textNodes.size > 0) {
  4984. const textChildren = this.#textChildren;
  4985. for (const [id, nodeIndex] of this.#textNodes) {
  4986. const element = document.getElementById(id);
  4987. if (!element) {
  4988. this.#textNodes.delete(id);
  4989. continue;
  4990. }
  4991. this.#addIdToAriaOwns(id, textChildren[nodeIndex]);
  4992. }
  4993. }
  4994. for (const [element, isRemovable] of this.#waitingElements) {
  4995. this.addPointerInTextLayer(element, isRemovable);
  4996. }
  4997. this.#waitingElements.clear();
  4998. }
  4999. disable() {
  5000. if (!this.#enabled) {
  5001. return;
  5002. }
  5003. this.#waitingElements.clear();
  5004. this.#textChildren = null;
  5005. this.#enabled = false;
  5006. }
  5007. removePointerInTextLayer(element) {
  5008. if (!this.#enabled) {
  5009. this.#waitingElements.delete(element);
  5010. return;
  5011. }
  5012. const children = this.#textChildren;
  5013. if (!children || children.length === 0) {
  5014. return;
  5015. }
  5016. const {
  5017. id
  5018. } = element;
  5019. const nodeIndex = this.#textNodes.get(id);
  5020. if (nodeIndex === undefined) {
  5021. return;
  5022. }
  5023. const node = children[nodeIndex];
  5024. this.#textNodes.delete(id);
  5025. let owns = node.getAttribute("aria-owns");
  5026. if (owns?.includes(id)) {
  5027. owns = owns.split(" ").filter(x => x !== id).join(" ");
  5028. if (owns) {
  5029. node.setAttribute("aria-owns", owns);
  5030. } else {
  5031. node.removeAttribute("aria-owns");
  5032. node.setAttribute("role", "presentation");
  5033. }
  5034. }
  5035. }
  5036. #addIdToAriaOwns(id, node) {
  5037. const owns = node.getAttribute("aria-owns");
  5038. if (!owns?.includes(id)) {
  5039. node.setAttribute("aria-owns", owns ? `${owns} ${id}` : id);
  5040. }
  5041. node.removeAttribute("role");
  5042. }
  5043. addPointerInTextLayer(element, isRemovable) {
  5044. const {
  5045. id
  5046. } = element;
  5047. if (!id) {
  5048. return;
  5049. }
  5050. if (!this.#enabled) {
  5051. this.#waitingElements.set(element, isRemovable);
  5052. return;
  5053. }
  5054. if (isRemovable) {
  5055. this.removePointerInTextLayer(element);
  5056. }
  5057. const children = this.#textChildren;
  5058. if (!children || children.length === 0) {
  5059. return;
  5060. }
  5061. const index = (0, _ui_utils.binarySearchFirstItem)(children, node => TextAccessibilityManager.#compareElementPositions(element, node) < 0);
  5062. const nodeIndex = Math.max(0, index - 1);
  5063. this.#addIdToAriaOwns(id, children[nodeIndex]);
  5064. this.#textNodes.set(id, nodeIndex);
  5065. }
  5066. moveElementInDOM(container, element, contentElement, isRemovable) {
  5067. this.addPointerInTextLayer(contentElement, isRemovable);
  5068. if (!container.hasChildNodes()) {
  5069. container.append(element);
  5070. return;
  5071. }
  5072. const children = Array.from(container.childNodes).filter(node => node !== element);
  5073. if (children.length === 0) {
  5074. return;
  5075. }
  5076. const elementToCompare = contentElement || element;
  5077. const index = (0, _ui_utils.binarySearchFirstItem)(children, node => TextAccessibilityManager.#compareElementPositions(elementToCompare, node) < 0);
  5078. if (index === 0) {
  5079. children[0].before(element);
  5080. } else {
  5081. children[index - 1].after(element);
  5082. }
  5083. }
  5084. }
  5085. exports.TextAccessibilityManager = TextAccessibilityManager;
  5086. /***/ }),
  5087. /* 21 */
  5088. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  5089. Object.defineProperty(exports, "__esModule", ({
  5090. value: true
  5091. }));
  5092. exports.PDFScriptingManager = void 0;
  5093. var _ui_utils = __w_pdfjs_require__(6);
  5094. var _pdfjsLib = __w_pdfjs_require__(3);
  5095. class PDFScriptingManager {
  5096. constructor({
  5097. eventBus,
  5098. sandboxBundleSrc = null,
  5099. scriptingFactory = null,
  5100. docPropertiesLookup = null
  5101. }) {
  5102. this._pdfDocument = null;
  5103. this._pdfViewer = null;
  5104. this._closeCapability = null;
  5105. this._destroyCapability = null;
  5106. this._scripting = null;
  5107. this._mouseState = Object.create(null);
  5108. this._ready = false;
  5109. this._eventBus = eventBus;
  5110. this._sandboxBundleSrc = sandboxBundleSrc;
  5111. this._scriptingFactory = scriptingFactory;
  5112. this._docPropertiesLookup = docPropertiesLookup;
  5113. if (!this._scriptingFactory) {
  5114. window.addEventListener("updatefromsandbox", event => {
  5115. this._eventBus.dispatch("updatefromsandbox", {
  5116. source: window,
  5117. detail: event.detail
  5118. });
  5119. });
  5120. }
  5121. }
  5122. setViewer(pdfViewer) {
  5123. this._pdfViewer = pdfViewer;
  5124. }
  5125. async setDocument(pdfDocument) {
  5126. if (this._pdfDocument) {
  5127. await this._destroyScripting();
  5128. }
  5129. this._pdfDocument = pdfDocument;
  5130. if (!pdfDocument) {
  5131. return;
  5132. }
  5133. const [objects, calculationOrder, docActions] = await Promise.all([pdfDocument.getFieldObjects(), pdfDocument.getCalculationOrderIds(), pdfDocument.getJSActions()]);
  5134. if (!objects && !docActions) {
  5135. await this._destroyScripting();
  5136. return;
  5137. }
  5138. if (pdfDocument !== this._pdfDocument) {
  5139. return;
  5140. }
  5141. try {
  5142. this._scripting = this._createScripting();
  5143. } catch (error) {
  5144. console.error(`PDFScriptingManager.setDocument: "${error?.message}".`);
  5145. await this._destroyScripting();
  5146. return;
  5147. }
  5148. this._internalEvents.set("updatefromsandbox", event => {
  5149. if (event?.source !== window) {
  5150. return;
  5151. }
  5152. this._updateFromSandbox(event.detail);
  5153. });
  5154. this._internalEvents.set("dispatcheventinsandbox", event => {
  5155. this._scripting?.dispatchEventInSandbox(event.detail);
  5156. });
  5157. this._internalEvents.set("pagechanging", ({
  5158. pageNumber,
  5159. previous
  5160. }) => {
  5161. if (pageNumber === previous) {
  5162. return;
  5163. }
  5164. this._dispatchPageClose(previous);
  5165. this._dispatchPageOpen(pageNumber);
  5166. });
  5167. this._internalEvents.set("pagerendered", ({
  5168. pageNumber
  5169. }) => {
  5170. if (!this._pageOpenPending.has(pageNumber)) {
  5171. return;
  5172. }
  5173. if (pageNumber !== this._pdfViewer.currentPageNumber) {
  5174. return;
  5175. }
  5176. this._dispatchPageOpen(pageNumber);
  5177. });
  5178. this._internalEvents.set("pagesdestroy", async event => {
  5179. await this._dispatchPageClose(this._pdfViewer.currentPageNumber);
  5180. await this._scripting?.dispatchEventInSandbox({
  5181. id: "doc",
  5182. name: "WillClose"
  5183. });
  5184. this._closeCapability?.resolve();
  5185. });
  5186. this._domEvents.set("mousedown", event => {
  5187. this._mouseState.isDown = true;
  5188. });
  5189. this._domEvents.set("mouseup", event => {
  5190. this._mouseState.isDown = false;
  5191. });
  5192. for (const [name, listener] of this._internalEvents) {
  5193. this._eventBus._on(name, listener);
  5194. }
  5195. for (const [name, listener] of this._domEvents) {
  5196. window.addEventListener(name, listener, true);
  5197. }
  5198. try {
  5199. const docProperties = await this._getDocProperties();
  5200. if (pdfDocument !== this._pdfDocument) {
  5201. return;
  5202. }
  5203. await this._scripting.createSandbox({
  5204. objects,
  5205. calculationOrder,
  5206. appInfo: {
  5207. platform: navigator.platform,
  5208. language: navigator.language
  5209. },
  5210. docInfo: {
  5211. ...docProperties,
  5212. actions: docActions
  5213. }
  5214. });
  5215. this._eventBus.dispatch("sandboxcreated", {
  5216. source: this
  5217. });
  5218. } catch (error) {
  5219. console.error(`PDFScriptingManager.setDocument: "${error?.message}".`);
  5220. await this._destroyScripting();
  5221. return;
  5222. }
  5223. await this._scripting?.dispatchEventInSandbox({
  5224. id: "doc",
  5225. name: "Open"
  5226. });
  5227. await this._dispatchPageOpen(this._pdfViewer.currentPageNumber, true);
  5228. Promise.resolve().then(() => {
  5229. if (pdfDocument === this._pdfDocument) {
  5230. this._ready = true;
  5231. }
  5232. });
  5233. }
  5234. async dispatchWillSave(detail) {
  5235. return this._scripting?.dispatchEventInSandbox({
  5236. id: "doc",
  5237. name: "WillSave"
  5238. });
  5239. }
  5240. async dispatchDidSave(detail) {
  5241. return this._scripting?.dispatchEventInSandbox({
  5242. id: "doc",
  5243. name: "DidSave"
  5244. });
  5245. }
  5246. async dispatchWillPrint(detail) {
  5247. return this._scripting?.dispatchEventInSandbox({
  5248. id: "doc",
  5249. name: "WillPrint"
  5250. });
  5251. }
  5252. async dispatchDidPrint(detail) {
  5253. return this._scripting?.dispatchEventInSandbox({
  5254. id: "doc",
  5255. name: "DidPrint"
  5256. });
  5257. }
  5258. get mouseState() {
  5259. return this._mouseState;
  5260. }
  5261. get destroyPromise() {
  5262. return this._destroyCapability?.promise || null;
  5263. }
  5264. get ready() {
  5265. return this._ready;
  5266. }
  5267. get _internalEvents() {
  5268. return (0, _pdfjsLib.shadow)(this, "_internalEvents", new Map());
  5269. }
  5270. get _domEvents() {
  5271. return (0, _pdfjsLib.shadow)(this, "_domEvents", new Map());
  5272. }
  5273. get _pageOpenPending() {
  5274. return (0, _pdfjsLib.shadow)(this, "_pageOpenPending", new Set());
  5275. }
  5276. get _visitedPages() {
  5277. return (0, _pdfjsLib.shadow)(this, "_visitedPages", new Map());
  5278. }
  5279. async _updateFromSandbox(detail) {
  5280. const isInPresentationMode = this._pdfViewer.isInPresentationMode || this._pdfViewer.isChangingPresentationMode;
  5281. const {
  5282. id,
  5283. siblings,
  5284. command,
  5285. value
  5286. } = detail;
  5287. if (!id) {
  5288. switch (command) {
  5289. case "clear":
  5290. console.clear();
  5291. break;
  5292. case "error":
  5293. console.error(value);
  5294. break;
  5295. case "layout":
  5296. if (isInPresentationMode) {
  5297. return;
  5298. }
  5299. const modes = (0, _ui_utils.apiPageLayoutToViewerModes)(value);
  5300. this._pdfViewer.spreadMode = modes.spreadMode;
  5301. break;
  5302. case "page-num":
  5303. this._pdfViewer.currentPageNumber = value + 1;
  5304. break;
  5305. case "print":
  5306. await this._pdfViewer.pagesPromise;
  5307. this._eventBus.dispatch("print", {
  5308. source: this
  5309. });
  5310. break;
  5311. case "println":
  5312. console.log(value);
  5313. break;
  5314. case "zoom":
  5315. if (isInPresentationMode) {
  5316. return;
  5317. }
  5318. this._pdfViewer.currentScaleValue = value;
  5319. break;
  5320. case "SaveAs":
  5321. this._eventBus.dispatch("download", {
  5322. source: this
  5323. });
  5324. break;
  5325. case "FirstPage":
  5326. this._pdfViewer.currentPageNumber = 1;
  5327. break;
  5328. case "LastPage":
  5329. this._pdfViewer.currentPageNumber = this._pdfViewer.pagesCount;
  5330. break;
  5331. case "NextPage":
  5332. this._pdfViewer.nextPage();
  5333. break;
  5334. case "PrevPage":
  5335. this._pdfViewer.previousPage();
  5336. break;
  5337. case "ZoomViewIn":
  5338. if (isInPresentationMode) {
  5339. return;
  5340. }
  5341. this._pdfViewer.increaseScale();
  5342. break;
  5343. case "ZoomViewOut":
  5344. if (isInPresentationMode) {
  5345. return;
  5346. }
  5347. this._pdfViewer.decreaseScale();
  5348. break;
  5349. }
  5350. return;
  5351. }
  5352. if (isInPresentationMode) {
  5353. if (detail.focus) {
  5354. return;
  5355. }
  5356. }
  5357. delete detail.id;
  5358. delete detail.siblings;
  5359. const ids = siblings ? [id, ...siblings] : [id];
  5360. for (const elementId of ids) {
  5361. const element = document.querySelector(`[data-element-id="${elementId}"]`);
  5362. if (element) {
  5363. element.dispatchEvent(new CustomEvent("updatefromsandbox", {
  5364. detail
  5365. }));
  5366. } else {
  5367. this._pdfDocument?.annotationStorage.setValue(elementId, detail);
  5368. }
  5369. }
  5370. }
  5371. async _dispatchPageOpen(pageNumber, initialize = false) {
  5372. const pdfDocument = this._pdfDocument,
  5373. visitedPages = this._visitedPages;
  5374. if (initialize) {
  5375. this._closeCapability = (0, _pdfjsLib.createPromiseCapability)();
  5376. }
  5377. if (!this._closeCapability) {
  5378. return;
  5379. }
  5380. const pageView = this._pdfViewer.getPageView(pageNumber - 1);
  5381. if (pageView?.renderingState !== _ui_utils.RenderingStates.FINISHED) {
  5382. this._pageOpenPending.add(pageNumber);
  5383. return;
  5384. }
  5385. this._pageOpenPending.delete(pageNumber);
  5386. const actionsPromise = (async () => {
  5387. const actions = await (!visitedPages.has(pageNumber) ? pageView.pdfPage?.getJSActions() : null);
  5388. if (pdfDocument !== this._pdfDocument) {
  5389. return;
  5390. }
  5391. await this._scripting?.dispatchEventInSandbox({
  5392. id: "page",
  5393. name: "PageOpen",
  5394. pageNumber,
  5395. actions
  5396. });
  5397. })();
  5398. visitedPages.set(pageNumber, actionsPromise);
  5399. }
  5400. async _dispatchPageClose(pageNumber) {
  5401. const pdfDocument = this._pdfDocument,
  5402. visitedPages = this._visitedPages;
  5403. if (!this._closeCapability) {
  5404. return;
  5405. }
  5406. if (this._pageOpenPending.has(pageNumber)) {
  5407. return;
  5408. }
  5409. const actionsPromise = visitedPages.get(pageNumber);
  5410. if (!actionsPromise) {
  5411. return;
  5412. }
  5413. visitedPages.set(pageNumber, null);
  5414. await actionsPromise;
  5415. if (pdfDocument !== this._pdfDocument) {
  5416. return;
  5417. }
  5418. await this._scripting?.dispatchEventInSandbox({
  5419. id: "page",
  5420. name: "PageClose",
  5421. pageNumber
  5422. });
  5423. }
  5424. async _getDocProperties() {
  5425. if (this._docPropertiesLookup) {
  5426. return this._docPropertiesLookup(this._pdfDocument);
  5427. }
  5428. const {
  5429. docPropertiesLookup
  5430. } = __w_pdfjs_require__(22);
  5431. return docPropertiesLookup(this._pdfDocument);
  5432. }
  5433. _createScripting() {
  5434. this._destroyCapability = (0, _pdfjsLib.createPromiseCapability)();
  5435. if (this._scripting) {
  5436. throw new Error("_createScripting: Scripting already exists.");
  5437. }
  5438. if (this._scriptingFactory) {
  5439. return this._scriptingFactory.createScripting({
  5440. sandboxBundleSrc: this._sandboxBundleSrc
  5441. });
  5442. }
  5443. const {
  5444. GenericScripting
  5445. } = __w_pdfjs_require__(22);
  5446. return new GenericScripting(this._sandboxBundleSrc);
  5447. }
  5448. async _destroyScripting() {
  5449. if (!this._scripting) {
  5450. this._pdfDocument = null;
  5451. this._destroyCapability?.resolve();
  5452. return;
  5453. }
  5454. if (this._closeCapability) {
  5455. await Promise.race([this._closeCapability.promise, new Promise(resolve => {
  5456. setTimeout(resolve, 1000);
  5457. })]).catch(reason => {});
  5458. this._closeCapability = null;
  5459. }
  5460. this._pdfDocument = null;
  5461. try {
  5462. await this._scripting.destroySandbox();
  5463. } catch (ex) {}
  5464. for (const [name, listener] of this._internalEvents) {
  5465. this._eventBus._off(name, listener);
  5466. }
  5467. this._internalEvents.clear();
  5468. for (const [name, listener] of this._domEvents) {
  5469. window.removeEventListener(name, listener, true);
  5470. }
  5471. this._domEvents.clear();
  5472. this._pageOpenPending.clear();
  5473. this._visitedPages.clear();
  5474. this._scripting = null;
  5475. delete this._mouseState.isDown;
  5476. this._ready = false;
  5477. this._destroyCapability?.resolve();
  5478. }
  5479. }
  5480. exports.PDFScriptingManager = PDFScriptingManager;
  5481. /***/ }),
  5482. /* 22 */
  5483. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  5484. Object.defineProperty(exports, "__esModule", ({
  5485. value: true
  5486. }));
  5487. exports.GenericScripting = void 0;
  5488. exports.docPropertiesLookup = docPropertiesLookup;
  5489. var _pdfjsLib = __w_pdfjs_require__(3);
  5490. async function docPropertiesLookup(pdfDocument) {
  5491. const url = "",
  5492. baseUrl = url.split("#")[0];
  5493. let {
  5494. info,
  5495. metadata,
  5496. contentDispositionFilename,
  5497. contentLength
  5498. } = await pdfDocument.getMetadata();
  5499. if (!contentLength) {
  5500. const {
  5501. length
  5502. } = await pdfDocument.getDownloadInfo();
  5503. contentLength = length;
  5504. }
  5505. return {
  5506. ...info,
  5507. baseURL: baseUrl,
  5508. filesize: contentLength,
  5509. filename: contentDispositionFilename || (0, _pdfjsLib.getPdfFilenameFromUrl)(url),
  5510. metadata: metadata?.getRaw(),
  5511. authors: metadata?.get("dc:creator"),
  5512. numPages: pdfDocument.numPages,
  5513. URL: url
  5514. };
  5515. }
  5516. class GenericScripting {
  5517. constructor(sandboxBundleSrc) {
  5518. this._ready = (0, _pdfjsLib.loadScript)(sandboxBundleSrc, true).then(() => {
  5519. return window.pdfjsSandbox.QuickJSSandbox();
  5520. });
  5521. }
  5522. async createSandbox(data) {
  5523. const sandbox = await this._ready;
  5524. sandbox.create(data);
  5525. }
  5526. async dispatchEventInSandbox(event) {
  5527. const sandbox = await this._ready;
  5528. setTimeout(() => sandbox.dispatchEvent(event), 0);
  5529. }
  5530. async destroySandbox() {
  5531. const sandbox = await this._ready;
  5532. sandbox.nukeSandbox();
  5533. }
  5534. }
  5535. exports.GenericScripting = GenericScripting;
  5536. /***/ }),
  5537. /* 23 */
  5538. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  5539. Object.defineProperty(exports, "__esModule", ({
  5540. value: true
  5541. }));
  5542. exports.PDFSinglePageViewer = void 0;
  5543. var _ui_utils = __w_pdfjs_require__(6);
  5544. var _pdf_viewer = __w_pdfjs_require__(24);
  5545. class PDFSinglePageViewer extends _pdf_viewer.PDFViewer {
  5546. _resetView() {
  5547. super._resetView();
  5548. this._scrollMode = _ui_utils.ScrollMode.PAGE;
  5549. this._spreadMode = _ui_utils.SpreadMode.NONE;
  5550. }
  5551. set scrollMode(mode) {}
  5552. _updateScrollMode() {}
  5553. set spreadMode(mode) {}
  5554. _updateSpreadMode() {}
  5555. }
  5556. exports.PDFSinglePageViewer = PDFSinglePageViewer;
  5557. /***/ }),
  5558. /* 24 */
  5559. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  5560. Object.defineProperty(exports, "__esModule", ({
  5561. value: true
  5562. }));
  5563. exports.PagesCountLimit = exports.PDFViewer = exports.PDFPageViewBuffer = void 0;
  5564. var _pdfjsLib = __w_pdfjs_require__(3);
  5565. var _ui_utils = __w_pdfjs_require__(6);
  5566. var _annotation_editor_layer_builder = __w_pdfjs_require__(2);
  5567. var _annotation_layer_builder = __w_pdfjs_require__(5);
  5568. var _l10n_utils = __w_pdfjs_require__(4);
  5569. var _pdf_page_view = __w_pdfjs_require__(18);
  5570. var _pdf_rendering_queue = __w_pdfjs_require__(25);
  5571. var _pdf_link_service = __w_pdfjs_require__(7);
  5572. var _struct_tree_layer_builder = __w_pdfjs_require__(8);
  5573. var _text_highlighter = __w_pdfjs_require__(26);
  5574. var _text_layer_builder = __w_pdfjs_require__(9);
  5575. var _xfa_layer_builder = __w_pdfjs_require__(10);
  5576. const DEFAULT_CACHE_SIZE = 10;
  5577. const ENABLE_PERMISSIONS_CLASS = "enablePermissions";
  5578. const PagesCountLimit = {
  5579. FORCE_SCROLL_MODE_PAGE: 15000,
  5580. FORCE_LAZY_PAGE_INIT: 7500,
  5581. PAUSE_EAGER_PAGE_INIT: 250
  5582. };
  5583. exports.PagesCountLimit = PagesCountLimit;
  5584. function isValidAnnotationEditorMode(mode) {
  5585. return Object.values(_pdfjsLib.AnnotationEditorType).includes(mode) && mode !== _pdfjsLib.AnnotationEditorType.DISABLE;
  5586. }
  5587. class PDFPageViewBuffer {
  5588. #buf = new Set();
  5589. #size = 0;
  5590. constructor(size) {
  5591. this.#size = size;
  5592. }
  5593. push(view) {
  5594. const buf = this.#buf;
  5595. if (buf.has(view)) {
  5596. buf.delete(view);
  5597. }
  5598. buf.add(view);
  5599. if (buf.size > this.#size) {
  5600. this.#destroyFirstView();
  5601. }
  5602. }
  5603. resize(newSize, idsToKeep = null) {
  5604. this.#size = newSize;
  5605. const buf = this.#buf;
  5606. if (idsToKeep) {
  5607. const ii = buf.size;
  5608. let i = 1;
  5609. for (const view of buf) {
  5610. if (idsToKeep.has(view.id)) {
  5611. buf.delete(view);
  5612. buf.add(view);
  5613. }
  5614. if (++i > ii) {
  5615. break;
  5616. }
  5617. }
  5618. }
  5619. while (buf.size > this.#size) {
  5620. this.#destroyFirstView();
  5621. }
  5622. }
  5623. has(view) {
  5624. return this.#buf.has(view);
  5625. }
  5626. [Symbol.iterator]() {
  5627. return this.#buf.keys();
  5628. }
  5629. #destroyFirstView() {
  5630. const firstView = this.#buf.keys().next().value;
  5631. firstView?.destroy();
  5632. this.#buf.delete(firstView);
  5633. }
  5634. }
  5635. exports.PDFPageViewBuffer = PDFPageViewBuffer;
  5636. class PDFViewer {
  5637. #buffer = null;
  5638. #annotationEditorMode = _pdfjsLib.AnnotationEditorType.NONE;
  5639. #annotationEditorUIManager = null;
  5640. #annotationMode = _pdfjsLib.AnnotationMode.ENABLE_FORMS;
  5641. #enablePermissions = false;
  5642. #previousContainerHeight = 0;
  5643. #scrollModePageState = null;
  5644. #onVisibilityChange = null;
  5645. constructor(options) {
  5646. const viewerVersion = '3.1.81';
  5647. if (_pdfjsLib.version !== viewerVersion) {
  5648. throw new Error(`The API version "${_pdfjsLib.version}" does not match the Viewer version "${viewerVersion}".`);
  5649. }
  5650. this.container = options.container;
  5651. this.viewer = options.viewer || options.container.firstElementChild;
  5652. if (!(this.container?.tagName.toUpperCase() === "DIV" && this.viewer?.tagName.toUpperCase() === "DIV")) {
  5653. throw new Error("Invalid `container` and/or `viewer` option.");
  5654. }
  5655. if (this.container.offsetParent && getComputedStyle(this.container).position !== "absolute") {
  5656. throw new Error("The `container` must be absolutely positioned.");
  5657. }
  5658. this.eventBus = options.eventBus;
  5659. this.linkService = options.linkService || new _pdf_link_service.SimpleLinkService();
  5660. this.downloadManager = options.downloadManager || null;
  5661. this.findController = options.findController || null;
  5662. this._scriptingManager = options.scriptingManager || null;
  5663. this.removePageBorders = options.removePageBorders || false;
  5664. this.textLayerMode = options.textLayerMode ?? _ui_utils.TextLayerMode.ENABLE;
  5665. this.#annotationMode = options.annotationMode ?? _pdfjsLib.AnnotationMode.ENABLE_FORMS;
  5666. this.#annotationEditorMode = options.annotationEditorMode ?? _pdfjsLib.AnnotationEditorType.NONE;
  5667. this.imageResourcesPath = options.imageResourcesPath || "";
  5668. this.enablePrintAutoRotate = options.enablePrintAutoRotate || false;
  5669. this.renderer = options.renderer || _ui_utils.RendererType.CANVAS;
  5670. this.useOnlyCssZoom = options.useOnlyCssZoom || false;
  5671. this.maxCanvasPixels = options.maxCanvasPixels;
  5672. this.l10n = options.l10n || _l10n_utils.NullL10n;
  5673. this.#enablePermissions = options.enablePermissions || false;
  5674. this.pageColors = options.pageColors || null;
  5675. if (this.pageColors && !(CSS.supports("color", this.pageColors.background) && CSS.supports("color", this.pageColors.foreground))) {
  5676. if (this.pageColors.background || this.pageColors.foreground) {
  5677. console.warn("PDFViewer: Ignoring `pageColors`-option, since the browser doesn't support the values used.");
  5678. }
  5679. this.pageColors = null;
  5680. }
  5681. this.defaultRenderingQueue = !options.renderingQueue;
  5682. if (this.defaultRenderingQueue) {
  5683. this.renderingQueue = new _pdf_rendering_queue.PDFRenderingQueue();
  5684. this.renderingQueue.setViewer(this);
  5685. } else {
  5686. this.renderingQueue = options.renderingQueue;
  5687. }
  5688. this.scroll = (0, _ui_utils.watchScroll)(this.container, this._scrollUpdate.bind(this));
  5689. this.presentationModeState = _ui_utils.PresentationModeState.UNKNOWN;
  5690. this._onBeforeDraw = this._onAfterDraw = null;
  5691. this._resetView();
  5692. if (this.removePageBorders) {
  5693. this.viewer.classList.add("removePageBorders");
  5694. }
  5695. this.updateContainerHeightCss();
  5696. }
  5697. get pagesCount() {
  5698. return this._pages.length;
  5699. }
  5700. getPageView(index) {
  5701. return this._pages[index];
  5702. }
  5703. get pageViewsReady() {
  5704. if (!this._pagesCapability.settled) {
  5705. return false;
  5706. }
  5707. return this._pages.every(function (pageView) {
  5708. return pageView?.pdfPage;
  5709. });
  5710. }
  5711. get renderForms() {
  5712. return this.#annotationMode === _pdfjsLib.AnnotationMode.ENABLE_FORMS;
  5713. }
  5714. get enableScripting() {
  5715. return !!this._scriptingManager;
  5716. }
  5717. get currentPageNumber() {
  5718. return this._currentPageNumber;
  5719. }
  5720. set currentPageNumber(val) {
  5721. if (!Number.isInteger(val)) {
  5722. throw new Error("Invalid page number.");
  5723. }
  5724. if (!this.pdfDocument) {
  5725. return;
  5726. }
  5727. if (!this._setCurrentPageNumber(val, true)) {
  5728. console.error(`currentPageNumber: "${val}" is not a valid page.`);
  5729. }
  5730. }
  5731. _setCurrentPageNumber(val, resetCurrentPageView = false) {
  5732. if (this._currentPageNumber === val) {
  5733. if (resetCurrentPageView) {
  5734. this.#resetCurrentPageView();
  5735. }
  5736. return true;
  5737. }
  5738. if (!(0 < val && val <= this.pagesCount)) {
  5739. return false;
  5740. }
  5741. const previous = this._currentPageNumber;
  5742. this._currentPageNumber = val;
  5743. this.eventBus.dispatch("pagechanging", {
  5744. source: this,
  5745. pageNumber: val,
  5746. pageLabel: this._pageLabels?.[val - 1] ?? null,
  5747. previous
  5748. });
  5749. if (resetCurrentPageView) {
  5750. this.#resetCurrentPageView();
  5751. }
  5752. return true;
  5753. }
  5754. get currentPageLabel() {
  5755. return this._pageLabels?.[this._currentPageNumber - 1] ?? null;
  5756. }
  5757. set currentPageLabel(val) {
  5758. if (!this.pdfDocument) {
  5759. return;
  5760. }
  5761. let page = val | 0;
  5762. if (this._pageLabels) {
  5763. const i = this._pageLabels.indexOf(val);
  5764. if (i >= 0) {
  5765. page = i + 1;
  5766. }
  5767. }
  5768. if (!this._setCurrentPageNumber(page, true)) {
  5769. console.error(`currentPageLabel: "${val}" is not a valid page.`);
  5770. }
  5771. }
  5772. get currentScale() {
  5773. return this._currentScale !== _ui_utils.UNKNOWN_SCALE ? this._currentScale : _ui_utils.DEFAULT_SCALE;
  5774. }
  5775. set currentScale(val) {
  5776. if (isNaN(val)) {
  5777. throw new Error("Invalid numeric scale.");
  5778. }
  5779. if (!this.pdfDocument) {
  5780. return;
  5781. }
  5782. this._setScale(val, false);
  5783. }
  5784. get currentScaleValue() {
  5785. return this._currentScaleValue;
  5786. }
  5787. set currentScaleValue(val) {
  5788. if (!this.pdfDocument) {
  5789. return;
  5790. }
  5791. this._setScale(val, false);
  5792. }
  5793. get pagesRotation() {
  5794. return this._pagesRotation;
  5795. }
  5796. set pagesRotation(rotation) {
  5797. if (!(0, _ui_utils.isValidRotation)(rotation)) {
  5798. throw new Error("Invalid pages rotation angle.");
  5799. }
  5800. if (!this.pdfDocument) {
  5801. return;
  5802. }
  5803. rotation %= 360;
  5804. if (rotation < 0) {
  5805. rotation += 360;
  5806. }
  5807. if (this._pagesRotation === rotation) {
  5808. return;
  5809. }
  5810. this._pagesRotation = rotation;
  5811. const pageNumber = this._currentPageNumber;
  5812. const updateArgs = {
  5813. rotation
  5814. };
  5815. for (const pageView of this._pages) {
  5816. pageView.update(updateArgs);
  5817. }
  5818. if (this._currentScaleValue) {
  5819. this._setScale(this._currentScaleValue, true);
  5820. }
  5821. this.eventBus.dispatch("rotationchanging", {
  5822. source: this,
  5823. pagesRotation: rotation,
  5824. pageNumber
  5825. });
  5826. if (this.defaultRenderingQueue) {
  5827. this.update();
  5828. }
  5829. }
  5830. get firstPagePromise() {
  5831. return this.pdfDocument ? this._firstPageCapability.promise : null;
  5832. }
  5833. get onePageRendered() {
  5834. return this.pdfDocument ? this._onePageRenderedCapability.promise : null;
  5835. }
  5836. get pagesPromise() {
  5837. return this.pdfDocument ? this._pagesCapability.promise : null;
  5838. }
  5839. #initializePermissions(permissions) {
  5840. const params = {
  5841. annotationEditorMode: this.#annotationEditorMode,
  5842. annotationMode: this.#annotationMode,
  5843. textLayerMode: this.textLayerMode
  5844. };
  5845. if (!permissions) {
  5846. return params;
  5847. }
  5848. if (!permissions.includes(_pdfjsLib.PermissionFlag.COPY)) {
  5849. this.viewer.classList.add(ENABLE_PERMISSIONS_CLASS);
  5850. }
  5851. if (!permissions.includes(_pdfjsLib.PermissionFlag.MODIFY_CONTENTS)) {
  5852. params.annotationEditorMode = _pdfjsLib.AnnotationEditorType.DISABLE;
  5853. }
  5854. if (!permissions.includes(_pdfjsLib.PermissionFlag.MODIFY_ANNOTATIONS) && !permissions.includes(_pdfjsLib.PermissionFlag.FILL_INTERACTIVE_FORMS) && this.#annotationMode === _pdfjsLib.AnnotationMode.ENABLE_FORMS) {
  5855. params.annotationMode = _pdfjsLib.AnnotationMode.ENABLE;
  5856. }
  5857. return params;
  5858. }
  5859. #onePageRenderedOrForceFetch() {
  5860. if (document.visibilityState === "hidden" || !this.container.offsetParent || this._getVisiblePages().views.length === 0) {
  5861. return Promise.resolve();
  5862. }
  5863. const visibilityChangePromise = new Promise(resolve => {
  5864. this.#onVisibilityChange = () => {
  5865. if (document.visibilityState !== "hidden") {
  5866. return;
  5867. }
  5868. resolve();
  5869. document.removeEventListener("visibilitychange", this.#onVisibilityChange);
  5870. this.#onVisibilityChange = null;
  5871. };
  5872. document.addEventListener("visibilitychange", this.#onVisibilityChange);
  5873. });
  5874. return Promise.race([this._onePageRenderedCapability.promise, visibilityChangePromise]);
  5875. }
  5876. setDocument(pdfDocument) {
  5877. if (this.pdfDocument) {
  5878. this.eventBus.dispatch("pagesdestroy", {
  5879. source: this
  5880. });
  5881. this._cancelRendering();
  5882. this._resetView();
  5883. this.findController?.setDocument(null);
  5884. this._scriptingManager?.setDocument(null);
  5885. if (this.#annotationEditorUIManager) {
  5886. this.#annotationEditorUIManager.destroy();
  5887. this.#annotationEditorUIManager = null;
  5888. }
  5889. }
  5890. this.pdfDocument = pdfDocument;
  5891. if (!pdfDocument) {
  5892. return;
  5893. }
  5894. const isPureXfa = pdfDocument.isPureXfa;
  5895. const pagesCount = pdfDocument.numPages;
  5896. const firstPagePromise = pdfDocument.getPage(1);
  5897. const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig();
  5898. const permissionsPromise = this.#enablePermissions ? pdfDocument.getPermissions() : Promise.resolve();
  5899. if (pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) {
  5900. console.warn("Forcing PAGE-scrolling for performance reasons, given the length of the document.");
  5901. const mode = this._scrollMode = _ui_utils.ScrollMode.PAGE;
  5902. this.eventBus.dispatch("scrollmodechanged", {
  5903. source: this,
  5904. mode
  5905. });
  5906. }
  5907. this._pagesCapability.promise.then(() => {
  5908. this.eventBus.dispatch("pagesloaded", {
  5909. source: this,
  5910. pagesCount
  5911. });
  5912. }, () => {});
  5913. this._onBeforeDraw = evt => {
  5914. const pageView = this._pages[evt.pageNumber - 1];
  5915. if (!pageView) {
  5916. return;
  5917. }
  5918. this.#buffer.push(pageView);
  5919. };
  5920. this.eventBus._on("pagerender", this._onBeforeDraw);
  5921. this._onAfterDraw = evt => {
  5922. if (evt.cssTransform || this._onePageRenderedCapability.settled) {
  5923. return;
  5924. }
  5925. this._onePageRenderedCapability.resolve({
  5926. timestamp: evt.timestamp
  5927. });
  5928. this.eventBus._off("pagerendered", this._onAfterDraw);
  5929. this._onAfterDraw = null;
  5930. if (this.#onVisibilityChange) {
  5931. document.removeEventListener("visibilitychange", this.#onVisibilityChange);
  5932. this.#onVisibilityChange = null;
  5933. }
  5934. };
  5935. this.eventBus._on("pagerendered", this._onAfterDraw);
  5936. Promise.all([firstPagePromise, permissionsPromise]).then(([firstPdfPage, permissions]) => {
  5937. if (pdfDocument !== this.pdfDocument) {
  5938. return;
  5939. }
  5940. this._firstPageCapability.resolve(firstPdfPage);
  5941. this._optionalContentConfigPromise = optionalContentConfigPromise;
  5942. const {
  5943. annotationEditorMode,
  5944. annotationMode,
  5945. textLayerMode
  5946. } = this.#initializePermissions(permissions);
  5947. if (annotationEditorMode !== _pdfjsLib.AnnotationEditorType.DISABLE) {
  5948. const mode = annotationEditorMode;
  5949. if (isPureXfa) {
  5950. console.warn("Warning: XFA-editing is not implemented.");
  5951. } else if (isValidAnnotationEditorMode(mode)) {
  5952. this.#annotationEditorUIManager = new _pdfjsLib.AnnotationEditorUIManager(this.container, this.eventBus);
  5953. if (mode !== _pdfjsLib.AnnotationEditorType.NONE) {
  5954. this.#annotationEditorUIManager.updateMode(mode);
  5955. }
  5956. } else {
  5957. console.error(`Invalid AnnotationEditor mode: ${mode}`);
  5958. }
  5959. }
  5960. const viewerElement = this._scrollMode === _ui_utils.ScrollMode.PAGE ? null : this.viewer;
  5961. const scale = this.currentScale;
  5962. const viewport = firstPdfPage.getViewport({
  5963. scale: scale * _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS
  5964. });
  5965. const textLayerFactory = textLayerMode !== _ui_utils.TextLayerMode.DISABLE && !isPureXfa ? this : null;
  5966. const annotationLayerFactory = annotationMode !== _pdfjsLib.AnnotationMode.DISABLE ? this : null;
  5967. const xfaLayerFactory = isPureXfa ? this : null;
  5968. const annotationEditorLayerFactory = this.#annotationEditorUIManager ? this : null;
  5969. for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  5970. const pageView = new _pdf_page_view.PDFPageView({
  5971. container: viewerElement,
  5972. eventBus: this.eventBus,
  5973. id: pageNum,
  5974. scale,
  5975. defaultViewport: viewport.clone(),
  5976. optionalContentConfigPromise,
  5977. renderingQueue: this.renderingQueue,
  5978. textLayerFactory,
  5979. textLayerMode,
  5980. annotationLayerFactory,
  5981. annotationMode,
  5982. xfaLayerFactory,
  5983. annotationEditorLayerFactory,
  5984. textHighlighterFactory: this,
  5985. structTreeLayerFactory: this,
  5986. imageResourcesPath: this.imageResourcesPath,
  5987. renderer: this.renderer,
  5988. useOnlyCssZoom: this.useOnlyCssZoom,
  5989. maxCanvasPixels: this.maxCanvasPixels,
  5990. pageColors: this.pageColors,
  5991. l10n: this.l10n
  5992. });
  5993. this._pages.push(pageView);
  5994. }
  5995. const firstPageView = this._pages[0];
  5996. if (firstPageView) {
  5997. firstPageView.setPdfPage(firstPdfPage);
  5998. this.linkService.cachePageRef(1, firstPdfPage.ref);
  5999. }
  6000. if (this._scrollMode === _ui_utils.ScrollMode.PAGE) {
  6001. this.#ensurePageViewVisible();
  6002. } else if (this._spreadMode !== _ui_utils.SpreadMode.NONE) {
  6003. this._updateSpreadMode();
  6004. }
  6005. this.#onePageRenderedOrForceFetch().then(async () => {
  6006. this.findController?.setDocument(pdfDocument);
  6007. this._scriptingManager?.setDocument(pdfDocument);
  6008. if (this.#annotationEditorUIManager) {
  6009. this.eventBus.dispatch("annotationeditormodechanged", {
  6010. source: this,
  6011. mode: this.#annotationEditorMode
  6012. });
  6013. }
  6014. if (pdfDocument.loadingParams.disableAutoFetch || pagesCount > PagesCountLimit.FORCE_LAZY_PAGE_INIT) {
  6015. this._pagesCapability.resolve();
  6016. return;
  6017. }
  6018. let getPagesLeft = pagesCount - 1;
  6019. if (getPagesLeft <= 0) {
  6020. this._pagesCapability.resolve();
  6021. return;
  6022. }
  6023. for (let pageNum = 2; pageNum <= pagesCount; ++pageNum) {
  6024. const promise = pdfDocument.getPage(pageNum).then(pdfPage => {
  6025. const pageView = this._pages[pageNum - 1];
  6026. if (!pageView.pdfPage) {
  6027. pageView.setPdfPage(pdfPage);
  6028. }
  6029. this.linkService.cachePageRef(pageNum, pdfPage.ref);
  6030. if (--getPagesLeft === 0) {
  6031. this._pagesCapability.resolve();
  6032. }
  6033. }, reason => {
  6034. console.error(`Unable to get page ${pageNum} to initialize viewer`, reason);
  6035. if (--getPagesLeft === 0) {
  6036. this._pagesCapability.resolve();
  6037. }
  6038. });
  6039. if (pageNum % PagesCountLimit.PAUSE_EAGER_PAGE_INIT === 0) {
  6040. await promise;
  6041. }
  6042. }
  6043. });
  6044. this.eventBus.dispatch("pagesinit", {
  6045. source: this
  6046. });
  6047. pdfDocument.getMetadata().then(({
  6048. info
  6049. }) => {
  6050. if (pdfDocument !== this.pdfDocument) {
  6051. return;
  6052. }
  6053. if (info.Language) {
  6054. this.viewer.lang = info.Language;
  6055. }
  6056. });
  6057. if (this.defaultRenderingQueue) {
  6058. this.update();
  6059. }
  6060. }).catch(reason => {
  6061. console.error("Unable to initialize viewer", reason);
  6062. this._pagesCapability.reject(reason);
  6063. });
  6064. }
  6065. setPageLabels(labels) {
  6066. if (!this.pdfDocument) {
  6067. return;
  6068. }
  6069. if (!labels) {
  6070. this._pageLabels = null;
  6071. } else if (!(Array.isArray(labels) && this.pdfDocument.numPages === labels.length)) {
  6072. this._pageLabels = null;
  6073. console.error(`setPageLabels: Invalid page labels.`);
  6074. } else {
  6075. this._pageLabels = labels;
  6076. }
  6077. for (let i = 0, ii = this._pages.length; i < ii; i++) {
  6078. this._pages[i].setPageLabel(this._pageLabels?.[i] ?? null);
  6079. }
  6080. }
  6081. _resetView() {
  6082. this._pages = [];
  6083. this._currentPageNumber = 1;
  6084. this._currentScale = _ui_utils.UNKNOWN_SCALE;
  6085. this._currentScaleValue = null;
  6086. this._pageLabels = null;
  6087. this.#buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
  6088. this._location = null;
  6089. this._pagesRotation = 0;
  6090. this._optionalContentConfigPromise = null;
  6091. this._firstPageCapability = (0, _pdfjsLib.createPromiseCapability)();
  6092. this._onePageRenderedCapability = (0, _pdfjsLib.createPromiseCapability)();
  6093. this._pagesCapability = (0, _pdfjsLib.createPromiseCapability)();
  6094. this._scrollMode = _ui_utils.ScrollMode.VERTICAL;
  6095. this._previousScrollMode = _ui_utils.ScrollMode.UNKNOWN;
  6096. this._spreadMode = _ui_utils.SpreadMode.NONE;
  6097. this.#scrollModePageState = {
  6098. previousPageNumber: 1,
  6099. scrollDown: true,
  6100. pages: []
  6101. };
  6102. if (this._onBeforeDraw) {
  6103. this.eventBus._off("pagerender", this._onBeforeDraw);
  6104. this._onBeforeDraw = null;
  6105. }
  6106. if (this._onAfterDraw) {
  6107. this.eventBus._off("pagerendered", this._onAfterDraw);
  6108. this._onAfterDraw = null;
  6109. }
  6110. if (this.#onVisibilityChange) {
  6111. document.removeEventListener("visibilitychange", this.#onVisibilityChange);
  6112. this.#onVisibilityChange = null;
  6113. }
  6114. this.viewer.textContent = "";
  6115. this._updateScrollMode();
  6116. this.viewer.removeAttribute("lang");
  6117. this.viewer.classList.remove(ENABLE_PERMISSIONS_CLASS);
  6118. }
  6119. #ensurePageViewVisible() {
  6120. if (this._scrollMode !== _ui_utils.ScrollMode.PAGE) {
  6121. throw new Error("#ensurePageViewVisible: Invalid scrollMode value.");
  6122. }
  6123. const pageNumber = this._currentPageNumber,
  6124. state = this.#scrollModePageState,
  6125. viewer = this.viewer;
  6126. viewer.textContent = "";
  6127. state.pages.length = 0;
  6128. if (this._spreadMode === _ui_utils.SpreadMode.NONE && !this.isInPresentationMode) {
  6129. const pageView = this._pages[pageNumber - 1];
  6130. viewer.append(pageView.div);
  6131. state.pages.push(pageView);
  6132. } else {
  6133. const pageIndexSet = new Set(),
  6134. parity = this._spreadMode - 1;
  6135. if (parity === -1) {
  6136. pageIndexSet.add(pageNumber - 1);
  6137. } else if (pageNumber % 2 !== parity) {
  6138. pageIndexSet.add(pageNumber - 1);
  6139. pageIndexSet.add(pageNumber);
  6140. } else {
  6141. pageIndexSet.add(pageNumber - 2);
  6142. pageIndexSet.add(pageNumber - 1);
  6143. }
  6144. const spread = document.createElement("div");
  6145. spread.className = "spread";
  6146. if (this.isInPresentationMode) {
  6147. const dummyPage = document.createElement("div");
  6148. dummyPage.className = "dummyPage";
  6149. spread.append(dummyPage);
  6150. }
  6151. for (const i of pageIndexSet) {
  6152. const pageView = this._pages[i];
  6153. if (!pageView) {
  6154. continue;
  6155. }
  6156. spread.append(pageView.div);
  6157. state.pages.push(pageView);
  6158. }
  6159. viewer.append(spread);
  6160. }
  6161. state.scrollDown = pageNumber >= state.previousPageNumber;
  6162. state.previousPageNumber = pageNumber;
  6163. }
  6164. _scrollUpdate() {
  6165. if (this.pagesCount === 0) {
  6166. return;
  6167. }
  6168. this.update();
  6169. }
  6170. #scrollIntoView(pageView, pageSpot = null) {
  6171. const {
  6172. div,
  6173. id
  6174. } = pageView;
  6175. if (this._currentPageNumber !== id) {
  6176. this._setCurrentPageNumber(id);
  6177. }
  6178. if (this._scrollMode === _ui_utils.ScrollMode.PAGE) {
  6179. this.#ensurePageViewVisible();
  6180. this.update();
  6181. }
  6182. if (!pageSpot && !this.isInPresentationMode) {
  6183. const left = div.offsetLeft + div.clientLeft,
  6184. right = left + div.clientWidth;
  6185. const {
  6186. scrollLeft,
  6187. clientWidth
  6188. } = this.container;
  6189. if (this._scrollMode === _ui_utils.ScrollMode.HORIZONTAL || left < scrollLeft || right > scrollLeft + clientWidth) {
  6190. pageSpot = {
  6191. left: 0,
  6192. top: 0
  6193. };
  6194. }
  6195. }
  6196. (0, _ui_utils.scrollIntoView)(div, pageSpot);
  6197. if (!this._currentScaleValue && this._location) {
  6198. this._location = null;
  6199. }
  6200. }
  6201. #isSameScale(newScale) {
  6202. return newScale === this._currentScale || Math.abs(newScale - this._currentScale) < 1e-15;
  6203. }
  6204. _setScaleUpdatePages(newScale, newValue, noScroll = false, preset = false) {
  6205. this._currentScaleValue = newValue.toString();
  6206. if (this.#isSameScale(newScale)) {
  6207. if (preset) {
  6208. this.eventBus.dispatch("scalechanging", {
  6209. source: this,
  6210. scale: newScale,
  6211. presetValue: newValue
  6212. });
  6213. }
  6214. return;
  6215. }
  6216. _ui_utils.docStyle.setProperty("--scale-factor", newScale * _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS);
  6217. const updateArgs = {
  6218. scale: newScale
  6219. };
  6220. for (const pageView of this._pages) {
  6221. pageView.update(updateArgs);
  6222. }
  6223. this._currentScale = newScale;
  6224. if (!noScroll) {
  6225. let page = this._currentPageNumber,
  6226. dest;
  6227. if (this._location && !(this.isInPresentationMode || this.isChangingPresentationMode)) {
  6228. page = this._location.pageNumber;
  6229. dest = [null, {
  6230. name: "XYZ"
  6231. }, this._location.left, this._location.top, null];
  6232. }
  6233. this.scrollPageIntoView({
  6234. pageNumber: page,
  6235. destArray: dest,
  6236. allowNegativeOffset: true
  6237. });
  6238. }
  6239. this.eventBus.dispatch("scalechanging", {
  6240. source: this,
  6241. scale: newScale,
  6242. presetValue: preset ? newValue : undefined
  6243. });
  6244. if (this.defaultRenderingQueue) {
  6245. this.update();
  6246. }
  6247. this.updateContainerHeightCss();
  6248. }
  6249. get _pageWidthScaleFactor() {
  6250. if (this._spreadMode !== _ui_utils.SpreadMode.NONE && this._scrollMode !== _ui_utils.ScrollMode.HORIZONTAL) {
  6251. return 2;
  6252. }
  6253. return 1;
  6254. }
  6255. _setScale(value, noScroll = false) {
  6256. let scale = parseFloat(value);
  6257. if (scale > 0) {
  6258. this._setScaleUpdatePages(scale, value, noScroll, false);
  6259. } else {
  6260. const currentPage = this._pages[this._currentPageNumber - 1];
  6261. if (!currentPage) {
  6262. return;
  6263. }
  6264. let hPadding = _ui_utils.SCROLLBAR_PADDING,
  6265. vPadding = _ui_utils.VERTICAL_PADDING;
  6266. if (this.isInPresentationMode) {
  6267. hPadding = vPadding = 4;
  6268. } else if (this.removePageBorders) {
  6269. hPadding = vPadding = 0;
  6270. } else if (this._scrollMode === _ui_utils.ScrollMode.HORIZONTAL) {
  6271. [hPadding, vPadding] = [vPadding, hPadding];
  6272. }
  6273. const pageWidthScale = (this.container.clientWidth - hPadding) / currentPage.width * currentPage.scale / this._pageWidthScaleFactor;
  6274. const pageHeightScale = (this.container.clientHeight - vPadding) / currentPage.height * currentPage.scale;
  6275. switch (value) {
  6276. case "page-actual":
  6277. scale = 1;
  6278. break;
  6279. case "page-width":
  6280. scale = pageWidthScale;
  6281. break;
  6282. case "page-height":
  6283. scale = pageHeightScale;
  6284. break;
  6285. case "page-fit":
  6286. scale = Math.min(pageWidthScale, pageHeightScale);
  6287. break;
  6288. case "auto":
  6289. const horizontalScale = (0, _ui_utils.isPortraitOrientation)(currentPage) ? pageWidthScale : Math.min(pageHeightScale, pageWidthScale);
  6290. scale = Math.min(_ui_utils.MAX_AUTO_SCALE, horizontalScale);
  6291. break;
  6292. default:
  6293. console.error(`_setScale: "${value}" is an unknown zoom value.`);
  6294. return;
  6295. }
  6296. this._setScaleUpdatePages(scale, value, noScroll, true);
  6297. }
  6298. }
  6299. #resetCurrentPageView() {
  6300. const pageView = this._pages[this._currentPageNumber - 1];
  6301. if (this.isInPresentationMode) {
  6302. this._setScale(this._currentScaleValue, true);
  6303. }
  6304. this.#scrollIntoView(pageView);
  6305. }
  6306. pageLabelToPageNumber(label) {
  6307. if (!this._pageLabels) {
  6308. return null;
  6309. }
  6310. const i = this._pageLabels.indexOf(label);
  6311. if (i < 0) {
  6312. return null;
  6313. }
  6314. return i + 1;
  6315. }
  6316. scrollPageIntoView({
  6317. pageNumber,
  6318. destArray = null,
  6319. allowNegativeOffset = false,
  6320. ignoreDestinationZoom = false
  6321. }) {
  6322. if (!this.pdfDocument) {
  6323. return;
  6324. }
  6325. const pageView = Number.isInteger(pageNumber) && this._pages[pageNumber - 1];
  6326. if (!pageView) {
  6327. console.error(`scrollPageIntoView: "${pageNumber}" is not a valid pageNumber parameter.`);
  6328. return;
  6329. }
  6330. if (this.isInPresentationMode || !destArray) {
  6331. this._setCurrentPageNumber(pageNumber, true);
  6332. return;
  6333. }
  6334. let x = 0,
  6335. y = 0;
  6336. let width = 0,
  6337. height = 0,
  6338. widthScale,
  6339. heightScale;
  6340. const changeOrientation = pageView.rotation % 180 !== 0;
  6341. const pageWidth = (changeOrientation ? pageView.height : pageView.width) / pageView.scale / _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS;
  6342. const pageHeight = (changeOrientation ? pageView.width : pageView.height) / pageView.scale / _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS;
  6343. let scale = 0;
  6344. switch (destArray[1].name) {
  6345. case "XYZ":
  6346. x = destArray[2];
  6347. y = destArray[3];
  6348. scale = destArray[4];
  6349. x = x !== null ? x : 0;
  6350. y = y !== null ? y : pageHeight;
  6351. break;
  6352. case "Fit":
  6353. case "FitB":
  6354. scale = "page-fit";
  6355. break;
  6356. case "FitH":
  6357. case "FitBH":
  6358. y = destArray[2];
  6359. scale = "page-width";
  6360. if (y === null && this._location) {
  6361. x = this._location.left;
  6362. y = this._location.top;
  6363. } else if (typeof y !== "number" || y < 0) {
  6364. y = pageHeight;
  6365. }
  6366. break;
  6367. case "FitV":
  6368. case "FitBV":
  6369. x = destArray[2];
  6370. width = pageWidth;
  6371. height = pageHeight;
  6372. scale = "page-height";
  6373. break;
  6374. case "FitR":
  6375. x = destArray[2];
  6376. y = destArray[3];
  6377. width = destArray[4] - x;
  6378. height = destArray[5] - y;
  6379. const hPadding = this.removePageBorders ? 0 : _ui_utils.SCROLLBAR_PADDING;
  6380. const vPadding = this.removePageBorders ? 0 : _ui_utils.VERTICAL_PADDING;
  6381. widthScale = (this.container.clientWidth - hPadding) / width / _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS;
  6382. heightScale = (this.container.clientHeight - vPadding) / height / _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS;
  6383. scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
  6384. break;
  6385. default:
  6386. console.error(`scrollPageIntoView: "${destArray[1].name}" is not a valid destination type.`);
  6387. return;
  6388. }
  6389. if (!ignoreDestinationZoom) {
  6390. if (scale && scale !== this._currentScale) {
  6391. this.currentScaleValue = scale;
  6392. } else if (this._currentScale === _ui_utils.UNKNOWN_SCALE) {
  6393. this.currentScaleValue = _ui_utils.DEFAULT_SCALE_VALUE;
  6394. }
  6395. }
  6396. if (scale === "page-fit" && !destArray[4]) {
  6397. this.#scrollIntoView(pageView);
  6398. return;
  6399. }
  6400. const boundingRect = [pageView.viewport.convertToViewportPoint(x, y), pageView.viewport.convertToViewportPoint(x + width, y + height)];
  6401. let left = Math.min(boundingRect[0][0], boundingRect[1][0]);
  6402. let top = Math.min(boundingRect[0][1], boundingRect[1][1]);
  6403. if (!allowNegativeOffset) {
  6404. left = Math.max(left, 0);
  6405. top = Math.max(top, 0);
  6406. }
  6407. this.#scrollIntoView(pageView, {
  6408. left,
  6409. top
  6410. });
  6411. }
  6412. _updateLocation(firstPage) {
  6413. const currentScale = this._currentScale;
  6414. const currentScaleValue = this._currentScaleValue;
  6415. const normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ? Math.round(currentScale * 10000) / 100 : currentScaleValue;
  6416. const pageNumber = firstPage.id;
  6417. const currentPageView = this._pages[pageNumber - 1];
  6418. const container = this.container;
  6419. const topLeft = currentPageView.getPagePoint(container.scrollLeft - firstPage.x, container.scrollTop - firstPage.y);
  6420. const intLeft = Math.round(topLeft[0]);
  6421. const intTop = Math.round(topLeft[1]);
  6422. let pdfOpenParams = `#page=${pageNumber}`;
  6423. if (!this.isInPresentationMode) {
  6424. pdfOpenParams += `&zoom=${normalizedScaleValue},${intLeft},${intTop}`;
  6425. }
  6426. this._location = {
  6427. pageNumber,
  6428. scale: normalizedScaleValue,
  6429. top: intTop,
  6430. left: intLeft,
  6431. rotation: this._pagesRotation,
  6432. pdfOpenParams
  6433. };
  6434. }
  6435. update() {
  6436. const visible = this._getVisiblePages();
  6437. const visiblePages = visible.views,
  6438. numVisiblePages = visiblePages.length;
  6439. if (numVisiblePages === 0) {
  6440. return;
  6441. }
  6442. const newCacheSize = Math.max(DEFAULT_CACHE_SIZE, 2 * numVisiblePages + 1);
  6443. this.#buffer.resize(newCacheSize, visible.ids);
  6444. this.renderingQueue.renderHighestPriority(visible);
  6445. const isSimpleLayout = this._spreadMode === _ui_utils.SpreadMode.NONE && (this._scrollMode === _ui_utils.ScrollMode.PAGE || this._scrollMode === _ui_utils.ScrollMode.VERTICAL);
  6446. const currentId = this._currentPageNumber;
  6447. let stillFullyVisible = false;
  6448. for (const page of visiblePages) {
  6449. if (page.percent < 100) {
  6450. break;
  6451. }
  6452. if (page.id === currentId && isSimpleLayout) {
  6453. stillFullyVisible = true;
  6454. break;
  6455. }
  6456. }
  6457. this._setCurrentPageNumber(stillFullyVisible ? currentId : visiblePages[0].id);
  6458. this._updateLocation(visible.first);
  6459. this.eventBus.dispatch("updateviewarea", {
  6460. source: this,
  6461. location: this._location
  6462. });
  6463. }
  6464. containsElement(element) {
  6465. return this.container.contains(element);
  6466. }
  6467. focus() {
  6468. this.container.focus();
  6469. }
  6470. get _isContainerRtl() {
  6471. return getComputedStyle(this.container).direction === "rtl";
  6472. }
  6473. get isInPresentationMode() {
  6474. return this.presentationModeState === _ui_utils.PresentationModeState.FULLSCREEN;
  6475. }
  6476. get isChangingPresentationMode() {
  6477. return this.presentationModeState === _ui_utils.PresentationModeState.CHANGING;
  6478. }
  6479. get isHorizontalScrollbarEnabled() {
  6480. return this.isInPresentationMode ? false : this.container.scrollWidth > this.container.clientWidth;
  6481. }
  6482. get isVerticalScrollbarEnabled() {
  6483. return this.isInPresentationMode ? false : this.container.scrollHeight > this.container.clientHeight;
  6484. }
  6485. _getVisiblePages() {
  6486. const views = this._scrollMode === _ui_utils.ScrollMode.PAGE ? this.#scrollModePageState.pages : this._pages,
  6487. horizontal = this._scrollMode === _ui_utils.ScrollMode.HORIZONTAL,
  6488. rtl = horizontal && this._isContainerRtl;
  6489. return (0, _ui_utils.getVisibleElements)({
  6490. scrollEl: this.container,
  6491. views,
  6492. sortByVisibility: true,
  6493. horizontal,
  6494. rtl
  6495. });
  6496. }
  6497. isPageVisible(pageNumber) {
  6498. if (!this.pdfDocument) {
  6499. return false;
  6500. }
  6501. if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) {
  6502. console.error(`isPageVisible: "${pageNumber}" is not a valid page.`);
  6503. return false;
  6504. }
  6505. return this._getVisiblePages().ids.has(pageNumber);
  6506. }
  6507. isPageCached(pageNumber) {
  6508. if (!this.pdfDocument) {
  6509. return false;
  6510. }
  6511. if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) {
  6512. console.error(`isPageCached: "${pageNumber}" is not a valid page.`);
  6513. return false;
  6514. }
  6515. const pageView = this._pages[pageNumber - 1];
  6516. return this.#buffer.has(pageView);
  6517. }
  6518. cleanup() {
  6519. for (const pageView of this._pages) {
  6520. if (pageView.renderingState !== _ui_utils.RenderingStates.FINISHED) {
  6521. pageView.reset();
  6522. }
  6523. }
  6524. }
  6525. _cancelRendering() {
  6526. for (const pageView of this._pages) {
  6527. pageView.cancelRendering();
  6528. }
  6529. }
  6530. async #ensurePdfPageLoaded(pageView) {
  6531. if (pageView.pdfPage) {
  6532. return pageView.pdfPage;
  6533. }
  6534. try {
  6535. const pdfPage = await this.pdfDocument.getPage(pageView.id);
  6536. if (!pageView.pdfPage) {
  6537. pageView.setPdfPage(pdfPage);
  6538. }
  6539. if (!this.linkService._cachedPageNumber?.(pdfPage.ref)) {
  6540. this.linkService.cachePageRef(pageView.id, pdfPage.ref);
  6541. }
  6542. return pdfPage;
  6543. } catch (reason) {
  6544. console.error("Unable to get page for page view", reason);
  6545. return null;
  6546. }
  6547. }
  6548. #getScrollAhead(visible) {
  6549. if (visible.first?.id === 1) {
  6550. return true;
  6551. } else if (visible.last?.id === this.pagesCount) {
  6552. return false;
  6553. }
  6554. switch (this._scrollMode) {
  6555. case _ui_utils.ScrollMode.PAGE:
  6556. return this.#scrollModePageState.scrollDown;
  6557. case _ui_utils.ScrollMode.HORIZONTAL:
  6558. return this.scroll.right;
  6559. }
  6560. return this.scroll.down;
  6561. }
  6562. #toggleLoadingIconSpinner(visibleIds) {
  6563. for (const id of visibleIds) {
  6564. const pageView = this._pages[id - 1];
  6565. pageView?.toggleLoadingIconSpinner(true);
  6566. }
  6567. for (const pageView of this.#buffer) {
  6568. if (visibleIds.has(pageView.id)) {
  6569. continue;
  6570. }
  6571. pageView.toggleLoadingIconSpinner(false);
  6572. }
  6573. }
  6574. forceRendering(currentlyVisiblePages) {
  6575. const visiblePages = currentlyVisiblePages || this._getVisiblePages();
  6576. const scrollAhead = this.#getScrollAhead(visiblePages);
  6577. const preRenderExtra = this._spreadMode !== _ui_utils.SpreadMode.NONE && this._scrollMode !== _ui_utils.ScrollMode.HORIZONTAL;
  6578. const pageView = this.renderingQueue.getHighestPriority(visiblePages, this._pages, scrollAhead, preRenderExtra);
  6579. this.#toggleLoadingIconSpinner(visiblePages.ids);
  6580. if (pageView) {
  6581. this.#ensurePdfPageLoaded(pageView).then(() => {
  6582. this.renderingQueue.renderView(pageView);
  6583. });
  6584. return true;
  6585. }
  6586. return false;
  6587. }
  6588. createTextLayerBuilder({
  6589. textLayerDiv,
  6590. pageIndex,
  6591. viewport,
  6592. eventBus,
  6593. highlighter,
  6594. accessibilityManager = null
  6595. }) {
  6596. return new _text_layer_builder.TextLayerBuilder({
  6597. textLayerDiv,
  6598. eventBus,
  6599. pageIndex,
  6600. viewport,
  6601. highlighter,
  6602. accessibilityManager
  6603. });
  6604. }
  6605. createTextHighlighter({
  6606. pageIndex,
  6607. eventBus
  6608. }) {
  6609. return new _text_highlighter.TextHighlighter({
  6610. eventBus,
  6611. pageIndex,
  6612. findController: this.isInPresentationMode ? null : this.findController
  6613. });
  6614. }
  6615. createAnnotationLayerBuilder({
  6616. pageDiv,
  6617. pdfPage,
  6618. annotationStorage = this.pdfDocument?.annotationStorage,
  6619. imageResourcesPath = "",
  6620. renderForms = true,
  6621. l10n = _l10n_utils.NullL10n,
  6622. enableScripting = this.enableScripting,
  6623. hasJSActionsPromise = this.pdfDocument?.hasJSActions(),
  6624. mouseState = this._scriptingManager?.mouseState,
  6625. fieldObjectsPromise = this.pdfDocument?.getFieldObjects(),
  6626. annotationCanvasMap = null,
  6627. accessibilityManager = null
  6628. }) {
  6629. return new _annotation_layer_builder.AnnotationLayerBuilder({
  6630. pageDiv,
  6631. pdfPage,
  6632. annotationStorage,
  6633. imageResourcesPath,
  6634. renderForms,
  6635. linkService: this.linkService,
  6636. downloadManager: this.downloadManager,
  6637. l10n,
  6638. enableScripting,
  6639. hasJSActionsPromise,
  6640. mouseState,
  6641. fieldObjectsPromise,
  6642. annotationCanvasMap,
  6643. accessibilityManager
  6644. });
  6645. }
  6646. createAnnotationEditorLayerBuilder({
  6647. uiManager = this.#annotationEditorUIManager,
  6648. pageDiv,
  6649. pdfPage,
  6650. accessibilityManager = null,
  6651. l10n,
  6652. annotationStorage = this.pdfDocument?.annotationStorage
  6653. }) {
  6654. return new _annotation_editor_layer_builder.AnnotationEditorLayerBuilder({
  6655. uiManager,
  6656. pageDiv,
  6657. pdfPage,
  6658. annotationStorage,
  6659. accessibilityManager,
  6660. l10n
  6661. });
  6662. }
  6663. createXfaLayerBuilder({
  6664. pageDiv,
  6665. pdfPage,
  6666. annotationStorage = this.pdfDocument?.annotationStorage
  6667. }) {
  6668. return new _xfa_layer_builder.XfaLayerBuilder({
  6669. pageDiv,
  6670. pdfPage,
  6671. annotationStorage,
  6672. linkService: this.linkService
  6673. });
  6674. }
  6675. createStructTreeLayerBuilder({
  6676. pdfPage
  6677. }) {
  6678. return new _struct_tree_layer_builder.StructTreeLayerBuilder({
  6679. pdfPage
  6680. });
  6681. }
  6682. get hasEqualPageSizes() {
  6683. const firstPageView = this._pages[0];
  6684. for (let i = 1, ii = this._pages.length; i < ii; ++i) {
  6685. const pageView = this._pages[i];
  6686. if (pageView.width !== firstPageView.width || pageView.height !== firstPageView.height) {
  6687. return false;
  6688. }
  6689. }
  6690. return true;
  6691. }
  6692. getPagesOverview() {
  6693. return this._pages.map(pageView => {
  6694. const viewport = pageView.pdfPage.getViewport({
  6695. scale: 1
  6696. });
  6697. if (!this.enablePrintAutoRotate || (0, _ui_utils.isPortraitOrientation)(viewport)) {
  6698. return {
  6699. width: viewport.width,
  6700. height: viewport.height,
  6701. rotation: viewport.rotation
  6702. };
  6703. }
  6704. return {
  6705. width: viewport.height,
  6706. height: viewport.width,
  6707. rotation: (viewport.rotation - 90) % 360
  6708. };
  6709. });
  6710. }
  6711. get optionalContentConfigPromise() {
  6712. if (!this.pdfDocument) {
  6713. return Promise.resolve(null);
  6714. }
  6715. if (!this._optionalContentConfigPromise) {
  6716. console.error("optionalContentConfigPromise: Not initialized yet.");
  6717. return this.pdfDocument.getOptionalContentConfig();
  6718. }
  6719. return this._optionalContentConfigPromise;
  6720. }
  6721. set optionalContentConfigPromise(promise) {
  6722. if (!(promise instanceof Promise)) {
  6723. throw new Error(`Invalid optionalContentConfigPromise: ${promise}`);
  6724. }
  6725. if (!this.pdfDocument) {
  6726. return;
  6727. }
  6728. if (!this._optionalContentConfigPromise) {
  6729. return;
  6730. }
  6731. this._optionalContentConfigPromise = promise;
  6732. const updateArgs = {
  6733. optionalContentConfigPromise: promise
  6734. };
  6735. for (const pageView of this._pages) {
  6736. pageView.update(updateArgs);
  6737. }
  6738. this.update();
  6739. this.eventBus.dispatch("optionalcontentconfigchanged", {
  6740. source: this,
  6741. promise
  6742. });
  6743. }
  6744. get scrollMode() {
  6745. return this._scrollMode;
  6746. }
  6747. set scrollMode(mode) {
  6748. if (this._scrollMode === mode) {
  6749. return;
  6750. }
  6751. if (!(0, _ui_utils.isValidScrollMode)(mode)) {
  6752. throw new Error(`Invalid scroll mode: ${mode}`);
  6753. }
  6754. if (this.pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) {
  6755. return;
  6756. }
  6757. this._previousScrollMode = this._scrollMode;
  6758. this._scrollMode = mode;
  6759. this.eventBus.dispatch("scrollmodechanged", {
  6760. source: this,
  6761. mode
  6762. });
  6763. this._updateScrollMode(this._currentPageNumber);
  6764. }
  6765. _updateScrollMode(pageNumber = null) {
  6766. const scrollMode = this._scrollMode,
  6767. viewer = this.viewer;
  6768. viewer.classList.toggle("scrollHorizontal", scrollMode === _ui_utils.ScrollMode.HORIZONTAL);
  6769. viewer.classList.toggle("scrollWrapped", scrollMode === _ui_utils.ScrollMode.WRAPPED);
  6770. if (!this.pdfDocument || !pageNumber) {
  6771. return;
  6772. }
  6773. if (scrollMode === _ui_utils.ScrollMode.PAGE) {
  6774. this.#ensurePageViewVisible();
  6775. } else if (this._previousScrollMode === _ui_utils.ScrollMode.PAGE) {
  6776. this._updateSpreadMode();
  6777. }
  6778. if (this._currentScaleValue && isNaN(this._currentScaleValue)) {
  6779. this._setScale(this._currentScaleValue, true);
  6780. }
  6781. this._setCurrentPageNumber(pageNumber, true);
  6782. this.update();
  6783. }
  6784. get spreadMode() {
  6785. return this._spreadMode;
  6786. }
  6787. set spreadMode(mode) {
  6788. if (this._spreadMode === mode) {
  6789. return;
  6790. }
  6791. if (!(0, _ui_utils.isValidSpreadMode)(mode)) {
  6792. throw new Error(`Invalid spread mode: ${mode}`);
  6793. }
  6794. this._spreadMode = mode;
  6795. this.eventBus.dispatch("spreadmodechanged", {
  6796. source: this,
  6797. mode
  6798. });
  6799. this._updateSpreadMode(this._currentPageNumber);
  6800. }
  6801. _updateSpreadMode(pageNumber = null) {
  6802. if (!this.pdfDocument) {
  6803. return;
  6804. }
  6805. const viewer = this.viewer,
  6806. pages = this._pages;
  6807. if (this._scrollMode === _ui_utils.ScrollMode.PAGE) {
  6808. this.#ensurePageViewVisible();
  6809. } else {
  6810. viewer.textContent = "";
  6811. if (this._spreadMode === _ui_utils.SpreadMode.NONE) {
  6812. for (const pageView of this._pages) {
  6813. viewer.append(pageView.div);
  6814. }
  6815. } else {
  6816. const parity = this._spreadMode - 1;
  6817. let spread = null;
  6818. for (let i = 0, ii = pages.length; i < ii; ++i) {
  6819. if (spread === null) {
  6820. spread = document.createElement("div");
  6821. spread.className = "spread";
  6822. viewer.append(spread);
  6823. } else if (i % 2 === parity) {
  6824. spread = spread.cloneNode(false);
  6825. viewer.append(spread);
  6826. }
  6827. spread.append(pages[i].div);
  6828. }
  6829. }
  6830. }
  6831. if (!pageNumber) {
  6832. return;
  6833. }
  6834. if (this._currentScaleValue && isNaN(this._currentScaleValue)) {
  6835. this._setScale(this._currentScaleValue, true);
  6836. }
  6837. this._setCurrentPageNumber(pageNumber, true);
  6838. this.update();
  6839. }
  6840. _getPageAdvance(currentPageNumber, previous = false) {
  6841. switch (this._scrollMode) {
  6842. case _ui_utils.ScrollMode.WRAPPED:
  6843. {
  6844. const {
  6845. views
  6846. } = this._getVisiblePages(),
  6847. pageLayout = new Map();
  6848. for (const {
  6849. id,
  6850. y,
  6851. percent,
  6852. widthPercent
  6853. } of views) {
  6854. if (percent === 0 || widthPercent < 100) {
  6855. continue;
  6856. }
  6857. let yArray = pageLayout.get(y);
  6858. if (!yArray) {
  6859. pageLayout.set(y, yArray ||= []);
  6860. }
  6861. yArray.push(id);
  6862. }
  6863. for (const yArray of pageLayout.values()) {
  6864. const currentIndex = yArray.indexOf(currentPageNumber);
  6865. if (currentIndex === -1) {
  6866. continue;
  6867. }
  6868. const numPages = yArray.length;
  6869. if (numPages === 1) {
  6870. break;
  6871. }
  6872. if (previous) {
  6873. for (let i = currentIndex - 1, ii = 0; i >= ii; i--) {
  6874. const currentId = yArray[i],
  6875. expectedId = yArray[i + 1] - 1;
  6876. if (currentId < expectedId) {
  6877. return currentPageNumber - expectedId;
  6878. }
  6879. }
  6880. } else {
  6881. for (let i = currentIndex + 1, ii = numPages; i < ii; i++) {
  6882. const currentId = yArray[i],
  6883. expectedId = yArray[i - 1] + 1;
  6884. if (currentId > expectedId) {
  6885. return expectedId - currentPageNumber;
  6886. }
  6887. }
  6888. }
  6889. if (previous) {
  6890. const firstId = yArray[0];
  6891. if (firstId < currentPageNumber) {
  6892. return currentPageNumber - firstId + 1;
  6893. }
  6894. } else {
  6895. const lastId = yArray[numPages - 1];
  6896. if (lastId > currentPageNumber) {
  6897. return lastId - currentPageNumber + 1;
  6898. }
  6899. }
  6900. break;
  6901. }
  6902. break;
  6903. }
  6904. case _ui_utils.ScrollMode.HORIZONTAL:
  6905. {
  6906. break;
  6907. }
  6908. case _ui_utils.ScrollMode.PAGE:
  6909. case _ui_utils.ScrollMode.VERTICAL:
  6910. {
  6911. if (this._spreadMode === _ui_utils.SpreadMode.NONE) {
  6912. break;
  6913. }
  6914. const parity = this._spreadMode - 1;
  6915. if (previous && currentPageNumber % 2 !== parity) {
  6916. break;
  6917. } else if (!previous && currentPageNumber % 2 === parity) {
  6918. break;
  6919. }
  6920. const {
  6921. views
  6922. } = this._getVisiblePages(),
  6923. expectedId = previous ? currentPageNumber - 1 : currentPageNumber + 1;
  6924. for (const {
  6925. id,
  6926. percent,
  6927. widthPercent
  6928. } of views) {
  6929. if (id !== expectedId) {
  6930. continue;
  6931. }
  6932. if (percent > 0 && widthPercent === 100) {
  6933. return 2;
  6934. }
  6935. break;
  6936. }
  6937. break;
  6938. }
  6939. }
  6940. return 1;
  6941. }
  6942. nextPage() {
  6943. const currentPageNumber = this._currentPageNumber,
  6944. pagesCount = this.pagesCount;
  6945. if (currentPageNumber >= pagesCount) {
  6946. return false;
  6947. }
  6948. const advance = this._getPageAdvance(currentPageNumber, false) || 1;
  6949. this.currentPageNumber = Math.min(currentPageNumber + advance, pagesCount);
  6950. return true;
  6951. }
  6952. previousPage() {
  6953. const currentPageNumber = this._currentPageNumber;
  6954. if (currentPageNumber <= 1) {
  6955. return false;
  6956. }
  6957. const advance = this._getPageAdvance(currentPageNumber, true) || 1;
  6958. this.currentPageNumber = Math.max(currentPageNumber - advance, 1);
  6959. return true;
  6960. }
  6961. increaseScale(steps = 1) {
  6962. let newScale = this._currentScale;
  6963. do {
  6964. newScale = (newScale * _ui_utils.DEFAULT_SCALE_DELTA).toFixed(2);
  6965. newScale = Math.ceil(newScale * 10) / 10;
  6966. newScale = Math.min(_ui_utils.MAX_SCALE, newScale);
  6967. } while (--steps > 0 && newScale < _ui_utils.MAX_SCALE);
  6968. this.currentScaleValue = newScale;
  6969. }
  6970. decreaseScale(steps = 1) {
  6971. let newScale = this._currentScale;
  6972. do {
  6973. newScale = (newScale / _ui_utils.DEFAULT_SCALE_DELTA).toFixed(2);
  6974. newScale = Math.floor(newScale * 10) / 10;
  6975. newScale = Math.max(_ui_utils.MIN_SCALE, newScale);
  6976. } while (--steps > 0 && newScale > _ui_utils.MIN_SCALE);
  6977. this.currentScaleValue = newScale;
  6978. }
  6979. updateContainerHeightCss() {
  6980. const height = this.container.clientHeight;
  6981. if (height !== this.#previousContainerHeight) {
  6982. this.#previousContainerHeight = height;
  6983. _ui_utils.docStyle.setProperty("--viewer-container-height", `${height}px`);
  6984. }
  6985. }
  6986. get annotationEditorMode() {
  6987. return this.#annotationEditorUIManager ? this.#annotationEditorMode : _pdfjsLib.AnnotationEditorType.DISABLE;
  6988. }
  6989. set annotationEditorMode(mode) {
  6990. if (!this.#annotationEditorUIManager) {
  6991. throw new Error(`The AnnotationEditor is not enabled.`);
  6992. }
  6993. if (this.#annotationEditorMode === mode) {
  6994. return;
  6995. }
  6996. if (!isValidAnnotationEditorMode(mode)) {
  6997. throw new Error(`Invalid AnnotationEditor mode: ${mode}`);
  6998. }
  6999. if (!this.pdfDocument) {
  7000. return;
  7001. }
  7002. this.#annotationEditorMode = mode;
  7003. this.eventBus.dispatch("annotationeditormodechanged", {
  7004. source: this,
  7005. mode
  7006. });
  7007. this.#annotationEditorUIManager.updateMode(mode);
  7008. }
  7009. set annotationEditorParams({
  7010. type,
  7011. value
  7012. }) {
  7013. if (!this.#annotationEditorUIManager) {
  7014. throw new Error(`The AnnotationEditor is not enabled.`);
  7015. }
  7016. this.#annotationEditorUIManager.updateParams(type, value);
  7017. }
  7018. refresh() {
  7019. if (!this.pdfDocument) {
  7020. return;
  7021. }
  7022. const updateArgs = {};
  7023. for (const pageView of this._pages) {
  7024. pageView.update(updateArgs);
  7025. }
  7026. this.update();
  7027. }
  7028. }
  7029. exports.PDFViewer = PDFViewer;
  7030. /***/ }),
  7031. /* 25 */
  7032. /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
  7033. Object.defineProperty(exports, "__esModule", ({
  7034. value: true
  7035. }));
  7036. exports.PDFRenderingQueue = void 0;
  7037. var _pdfjsLib = __w_pdfjs_require__(3);
  7038. var _ui_utils = __w_pdfjs_require__(6);
  7039. const CLEANUP_TIMEOUT = 30000;
  7040. class PDFRenderingQueue {
  7041. constructor() {
  7042. this.pdfViewer = null;
  7043. this.pdfThumbnailViewer = null;
  7044. this.onIdle = null;
  7045. this.highestPriorityPage = null;
  7046. this.idleTimeout = null;
  7047. this.printing = false;
  7048. this.isThumbnailViewEnabled = false;
  7049. }
  7050. setViewer(pdfViewer) {
  7051. this.pdfViewer = pdfViewer;
  7052. }
  7053. setThumbnailViewer(pdfThumbnailViewer) {
  7054. this.pdfThumbnailViewer = pdfThumbnailViewer;
  7055. }
  7056. isHighestPriority(view) {
  7057. return this.highestPriorityPage === view.renderingId;
  7058. }
  7059. hasViewer() {
  7060. return !!this.pdfViewer;
  7061. }
  7062. renderHighestPriority(currentlyVisiblePages) {
  7063. if (this.idleTimeout) {
  7064. clearTimeout(this.idleTimeout);
  7065. this.idleTimeout = null;
  7066. }
  7067. if (this.pdfViewer.forceRendering(currentlyVisiblePages)) {
  7068. return;
  7069. }
  7070. if (this.isThumbnailViewEnabled && this.pdfThumbnailViewer?.forceRendering()) {
  7071. return;
  7072. }
  7073. if (this.printing) {
  7074. return;
  7075. }
  7076. if (this.onIdle) {
  7077. this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT);
  7078. }
  7079. }
  7080. getHighestPriority(visible, views, scrolledDown, preRenderExtra = false) {
  7081. const visibleViews = visible.views,
  7082. numVisible = visibleViews.length;
  7083. if (numVisible === 0) {
  7084. return null;
  7085. }
  7086. for (let i = 0; i < numVisible; i++) {
  7087. const view = visibleViews[i].view;
  7088. if (!this.isViewFinished(view)) {
  7089. return view;
  7090. }
  7091. }
  7092. const firstId = visible.first.id,
  7093. lastId = visible.last.id;
  7094. if (lastId - firstId + 1 > numVisible) {
  7095. const visibleIds = visible.ids;
  7096. for (let i = 1, ii = lastId - firstId; i < ii; i++) {
  7097. const holeId = scrolledDown ? firstId + i : lastId - i;
  7098. if (visibleIds.has(holeId)) {
  7099. continue;
  7100. }
  7101. const holeView = views[holeId - 1];
  7102. if (!this.isViewFinished(holeView)) {
  7103. return holeView;
  7104. }
  7105. }
  7106. }
  7107. let preRenderIndex = scrolledDown ? lastId : firstId - 2;
  7108. let preRenderView = views[preRenderIndex];
  7109. if (preRenderView && !this.isViewFinished(preRenderView)) {
  7110. return preRenderView;
  7111. }
  7112. if (preRenderExtra) {
  7113. preRenderIndex += scrolledDown ? 1 : -1;
  7114. preRenderView = views[preRenderIndex];
  7115. if (preRenderView && !this.isViewFinished(preRenderView)) {
  7116. return preRenderView;
  7117. }
  7118. }
  7119. return null;
  7120. }
  7121. isViewFinished(view) {
  7122. return view.renderingState === _ui_utils.RenderingStates.FINISHED;
  7123. }
  7124. renderView(view) {
  7125. switch (view.renderingState) {
  7126. case _ui_utils.RenderingStates.FINISHED:
  7127. return false;
  7128. case _ui_utils.RenderingStates.PAUSED:
  7129. this.highestPriorityPage = view.renderingId;
  7130. view.resume();
  7131. break;
  7132. case _ui_utils.RenderingStates.RUNNING:
  7133. this.highestPriorityPage = view.renderingId;
  7134. break;
  7135. case _ui_utils.RenderingStates.INITIAL:
  7136. this.highestPriorityPage = view.renderingId;
  7137. view.draw().finally(() => {
  7138. this.renderHighestPriority();
  7139. }).catch(reason => {
  7140. if (reason instanceof _pdfjsLib.RenderingCancelledException) {
  7141. return;
  7142. }
  7143. console.error(`renderView: "${reason}"`);
  7144. });
  7145. break;
  7146. }
  7147. return true;
  7148. }
  7149. }
  7150. exports.PDFRenderingQueue = PDFRenderingQueue;
  7151. /***/ }),
  7152. /* 26 */
  7153. /***/ ((__unused_webpack_module, exports) => {
  7154. Object.defineProperty(exports, "__esModule", ({
  7155. value: true
  7156. }));
  7157. exports.TextHighlighter = void 0;
  7158. class TextHighlighter {
  7159. constructor({
  7160. findController,
  7161. eventBus,
  7162. pageIndex
  7163. }) {
  7164. this.findController = findController;
  7165. this.matches = [];
  7166. this.eventBus = eventBus;
  7167. this.pageIdx = pageIndex;
  7168. this._onUpdateTextLayerMatches = null;
  7169. this.textDivs = null;
  7170. this.textContentItemsStr = null;
  7171. this.enabled = false;
  7172. }
  7173. setTextMapping(divs, texts) {
  7174. this.textDivs = divs;
  7175. this.textContentItemsStr = texts;
  7176. }
  7177. enable() {
  7178. if (!this.textDivs || !this.textContentItemsStr) {
  7179. throw new Error("Text divs and strings have not been set.");
  7180. }
  7181. if (this.enabled) {
  7182. throw new Error("TextHighlighter is already enabled.");
  7183. }
  7184. this.enabled = true;
  7185. if (!this._onUpdateTextLayerMatches) {
  7186. this._onUpdateTextLayerMatches = evt => {
  7187. if (evt.pageIndex === this.pageIdx || evt.pageIndex === -1) {
  7188. this._updateMatches();
  7189. }
  7190. };
  7191. this.eventBus._on("updatetextlayermatches", this._onUpdateTextLayerMatches);
  7192. }
  7193. this._updateMatches();
  7194. }
  7195. disable() {
  7196. if (!this.enabled) {
  7197. return;
  7198. }
  7199. this.enabled = false;
  7200. if (this._onUpdateTextLayerMatches) {
  7201. this.eventBus._off("updatetextlayermatches", this._onUpdateTextLayerMatches);
  7202. this._onUpdateTextLayerMatches = null;
  7203. }
  7204. }
  7205. _convertMatches(matches, matchesLength) {
  7206. if (!matches) {
  7207. return [];
  7208. }
  7209. const {
  7210. textContentItemsStr
  7211. } = this;
  7212. let i = 0,
  7213. iIndex = 0;
  7214. const end = textContentItemsStr.length - 1;
  7215. const result = [];
  7216. for (let m = 0, mm = matches.length; m < mm; m++) {
  7217. let matchIdx = matches[m];
  7218. while (i !== end && matchIdx >= iIndex + textContentItemsStr[i].length) {
  7219. iIndex += textContentItemsStr[i].length;
  7220. i++;
  7221. }
  7222. if (i === textContentItemsStr.length) {
  7223. console.error("Could not find a matching mapping");
  7224. }
  7225. const match = {
  7226. begin: {
  7227. divIdx: i,
  7228. offset: matchIdx - iIndex
  7229. }
  7230. };
  7231. matchIdx += matchesLength[m];
  7232. while (i !== end && matchIdx > iIndex + textContentItemsStr[i].length) {
  7233. iIndex += textContentItemsStr[i].length;
  7234. i++;
  7235. }
  7236. match.end = {
  7237. divIdx: i,
  7238. offset: matchIdx - iIndex
  7239. };
  7240. result.push(match);
  7241. }
  7242. return result;
  7243. }
  7244. _renderMatches(matches) {
  7245. if (matches.length === 0) {
  7246. return;
  7247. }
  7248. const {
  7249. findController,
  7250. pageIdx
  7251. } = this;
  7252. const {
  7253. textContentItemsStr,
  7254. textDivs
  7255. } = this;
  7256. const isSelectedPage = pageIdx === findController.selected.pageIdx;
  7257. const selectedMatchIdx = findController.selected.matchIdx;
  7258. const highlightAll = findController.state.highlightAll;
  7259. let prevEnd = null;
  7260. const infinity = {
  7261. divIdx: -1,
  7262. offset: undefined
  7263. };
  7264. function beginText(begin, className) {
  7265. const divIdx = begin.divIdx;
  7266. textDivs[divIdx].textContent = "";
  7267. return appendTextToDiv(divIdx, 0, begin.offset, className);
  7268. }
  7269. function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
  7270. let div = textDivs[divIdx];
  7271. if (div.nodeType === Node.TEXT_NODE) {
  7272. const span = document.createElement("span");
  7273. div.before(span);
  7274. span.append(div);
  7275. textDivs[divIdx] = span;
  7276. div = span;
  7277. }
  7278. const content = textContentItemsStr[divIdx].substring(fromOffset, toOffset);
  7279. const node = document.createTextNode(content);
  7280. if (className) {
  7281. const span = document.createElement("span");
  7282. span.className = `${className} appended`;
  7283. span.append(node);
  7284. div.append(span);
  7285. return className.includes("selected") ? span.offsetLeft : 0;
  7286. }
  7287. div.append(node);
  7288. return 0;
  7289. }
  7290. let i0 = selectedMatchIdx,
  7291. i1 = i0 + 1;
  7292. if (highlightAll) {
  7293. i0 = 0;
  7294. i1 = matches.length;
  7295. } else if (!isSelectedPage) {
  7296. return;
  7297. }
  7298. for (let i = i0; i < i1; i++) {
  7299. const match = matches[i];
  7300. const begin = match.begin;
  7301. const end = match.end;
  7302. const isSelected = isSelectedPage && i === selectedMatchIdx;
  7303. const highlightSuffix = isSelected ? " selected" : "";
  7304. let selectedLeft = 0;
  7305. if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
  7306. if (prevEnd !== null) {
  7307. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  7308. }
  7309. beginText(begin);
  7310. } else {
  7311. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
  7312. }
  7313. if (begin.divIdx === end.divIdx) {
  7314. selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, end.offset, "highlight" + highlightSuffix);
  7315. } else {
  7316. selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, "highlight begin" + highlightSuffix);
  7317. for (let n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
  7318. textDivs[n0].className = "highlight middle" + highlightSuffix;
  7319. }
  7320. beginText(end, "highlight end" + highlightSuffix);
  7321. }
  7322. prevEnd = end;
  7323. if (isSelected) {
  7324. findController.scrollMatchIntoView({
  7325. element: textDivs[begin.divIdx],
  7326. selectedLeft,
  7327. pageIndex: pageIdx,
  7328. matchIndex: selectedMatchIdx
  7329. });
  7330. }
  7331. }
  7332. if (prevEnd) {
  7333. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  7334. }
  7335. }
  7336. _updateMatches() {
  7337. if (!this.enabled) {
  7338. return;
  7339. }
  7340. const {
  7341. findController,
  7342. matches,
  7343. pageIdx
  7344. } = this;
  7345. const {
  7346. textContentItemsStr,
  7347. textDivs
  7348. } = this;
  7349. let clearedUntilDivIdx = -1;
  7350. for (const match of matches) {
  7351. const begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
  7352. for (let n = begin, end = match.end.divIdx; n <= end; n++) {
  7353. const div = textDivs[n];
  7354. div.textContent = textContentItemsStr[n];
  7355. div.className = "";
  7356. }
  7357. clearedUntilDivIdx = match.end.divIdx + 1;
  7358. }
  7359. if (!findController?.highlightMatches) {
  7360. return;
  7361. }
  7362. const pageMatches = findController.pageMatches[pageIdx] || null;
  7363. const pageMatchesLength = findController.pageMatchesLength[pageIdx] || null;
  7364. this.matches = this._convertMatches(pageMatches, pageMatchesLength);
  7365. this._renderMatches(this.matches);
  7366. }
  7367. }
  7368. exports.TextHighlighter = TextHighlighter;
  7369. /***/ })
  7370. /******/ ]);
  7371. /************************************************************************/
  7372. /******/ // The module cache
  7373. /******/ var __webpack_module_cache__ = {};
  7374. /******/
  7375. /******/ // The require function
  7376. /******/ function __w_pdfjs_require__(moduleId) {
  7377. /******/ // Check if module is in cache
  7378. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  7379. /******/ if (cachedModule !== undefined) {
  7380. /******/ return cachedModule.exports;
  7381. /******/ }
  7382. /******/ // Create a new module (and put it into the cache)
  7383. /******/ var module = __webpack_module_cache__[moduleId] = {
  7384. /******/ // no module.id needed
  7385. /******/ // no module.loaded needed
  7386. /******/ exports: {}
  7387. /******/ };
  7388. /******/
  7389. /******/ // Execute the module function
  7390. /******/ __webpack_modules__[moduleId](module, module.exports, __w_pdfjs_require__);
  7391. /******/
  7392. /******/ // Return the exports of the module
  7393. /******/ return module.exports;
  7394. /******/ }
  7395. /******/
  7396. /************************************************************************/
  7397. var __webpack_exports__ = {};
  7398. // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
  7399. (() => {
  7400. var exports = __webpack_exports__;
  7401. Object.defineProperty(exports, "__esModule", ({
  7402. value: true
  7403. }));
  7404. Object.defineProperty(exports, "AnnotationLayerBuilder", ({
  7405. enumerable: true,
  7406. get: function () {
  7407. return _annotation_layer_builder.AnnotationLayerBuilder;
  7408. }
  7409. }));
  7410. Object.defineProperty(exports, "DefaultAnnotationLayerFactory", ({
  7411. enumerable: true,
  7412. get: function () {
  7413. return _default_factory.DefaultAnnotationLayerFactory;
  7414. }
  7415. }));
  7416. Object.defineProperty(exports, "DefaultStructTreeLayerFactory", ({
  7417. enumerable: true,
  7418. get: function () {
  7419. return _default_factory.DefaultStructTreeLayerFactory;
  7420. }
  7421. }));
  7422. Object.defineProperty(exports, "DefaultTextLayerFactory", ({
  7423. enumerable: true,
  7424. get: function () {
  7425. return _default_factory.DefaultTextLayerFactory;
  7426. }
  7427. }));
  7428. Object.defineProperty(exports, "DefaultXfaLayerFactory", ({
  7429. enumerable: true,
  7430. get: function () {
  7431. return _default_factory.DefaultXfaLayerFactory;
  7432. }
  7433. }));
  7434. Object.defineProperty(exports, "DownloadManager", ({
  7435. enumerable: true,
  7436. get: function () {
  7437. return _download_manager.DownloadManager;
  7438. }
  7439. }));
  7440. Object.defineProperty(exports, "EventBus", ({
  7441. enumerable: true,
  7442. get: function () {
  7443. return _event_utils.EventBus;
  7444. }
  7445. }));
  7446. Object.defineProperty(exports, "GenericL10n", ({
  7447. enumerable: true,
  7448. get: function () {
  7449. return _genericl10n.GenericL10n;
  7450. }
  7451. }));
  7452. Object.defineProperty(exports, "LinkTarget", ({
  7453. enumerable: true,
  7454. get: function () {
  7455. return _pdf_link_service.LinkTarget;
  7456. }
  7457. }));
  7458. Object.defineProperty(exports, "NullL10n", ({
  7459. enumerable: true,
  7460. get: function () {
  7461. return _l10n_utils.NullL10n;
  7462. }
  7463. }));
  7464. Object.defineProperty(exports, "PDFFindController", ({
  7465. enumerable: true,
  7466. get: function () {
  7467. return _pdf_find_controller.PDFFindController;
  7468. }
  7469. }));
  7470. Object.defineProperty(exports, "PDFHistory", ({
  7471. enumerable: true,
  7472. get: function () {
  7473. return _pdf_history.PDFHistory;
  7474. }
  7475. }));
  7476. Object.defineProperty(exports, "PDFLinkService", ({
  7477. enumerable: true,
  7478. get: function () {
  7479. return _pdf_link_service.PDFLinkService;
  7480. }
  7481. }));
  7482. Object.defineProperty(exports, "PDFPageView", ({
  7483. enumerable: true,
  7484. get: function () {
  7485. return _pdf_page_view.PDFPageView;
  7486. }
  7487. }));
  7488. Object.defineProperty(exports, "PDFScriptingManager", ({
  7489. enumerable: true,
  7490. get: function () {
  7491. return _pdf_scripting_manager.PDFScriptingManager;
  7492. }
  7493. }));
  7494. Object.defineProperty(exports, "PDFSinglePageViewer", ({
  7495. enumerable: true,
  7496. get: function () {
  7497. return _pdf_single_page_viewer.PDFSinglePageViewer;
  7498. }
  7499. }));
  7500. Object.defineProperty(exports, "PDFViewer", ({
  7501. enumerable: true,
  7502. get: function () {
  7503. return _pdf_viewer.PDFViewer;
  7504. }
  7505. }));
  7506. Object.defineProperty(exports, "ProgressBar", ({
  7507. enumerable: true,
  7508. get: function () {
  7509. return _ui_utils.ProgressBar;
  7510. }
  7511. }));
  7512. Object.defineProperty(exports, "RenderingStates", ({
  7513. enumerable: true,
  7514. get: function () {
  7515. return _ui_utils.RenderingStates;
  7516. }
  7517. }));
  7518. Object.defineProperty(exports, "ScrollMode", ({
  7519. enumerable: true,
  7520. get: function () {
  7521. return _ui_utils.ScrollMode;
  7522. }
  7523. }));
  7524. Object.defineProperty(exports, "SimpleLinkService", ({
  7525. enumerable: true,
  7526. get: function () {
  7527. return _pdf_link_service.SimpleLinkService;
  7528. }
  7529. }));
  7530. Object.defineProperty(exports, "SpreadMode", ({
  7531. enumerable: true,
  7532. get: function () {
  7533. return _ui_utils.SpreadMode;
  7534. }
  7535. }));
  7536. Object.defineProperty(exports, "StructTreeLayerBuilder", ({
  7537. enumerable: true,
  7538. get: function () {
  7539. return _struct_tree_layer_builder.StructTreeLayerBuilder;
  7540. }
  7541. }));
  7542. Object.defineProperty(exports, "TextLayerBuilder", ({
  7543. enumerable: true,
  7544. get: function () {
  7545. return _text_layer_builder.TextLayerBuilder;
  7546. }
  7547. }));
  7548. Object.defineProperty(exports, "XfaLayerBuilder", ({
  7549. enumerable: true,
  7550. get: function () {
  7551. return _xfa_layer_builder.XfaLayerBuilder;
  7552. }
  7553. }));
  7554. Object.defineProperty(exports, "parseQueryString", ({
  7555. enumerable: true,
  7556. get: function () {
  7557. return _ui_utils.parseQueryString;
  7558. }
  7559. }));
  7560. var _default_factory = __w_pdfjs_require__(1);
  7561. var _pdf_link_service = __w_pdfjs_require__(7);
  7562. var _ui_utils = __w_pdfjs_require__(6);
  7563. var _annotation_layer_builder = __w_pdfjs_require__(5);
  7564. var _download_manager = __w_pdfjs_require__(11);
  7565. var _event_utils = __w_pdfjs_require__(12);
  7566. var _genericl10n = __w_pdfjs_require__(13);
  7567. var _l10n_utils = __w_pdfjs_require__(4);
  7568. var _pdf_find_controller = __w_pdfjs_require__(15);
  7569. var _pdf_history = __w_pdfjs_require__(17);
  7570. var _pdf_page_view = __w_pdfjs_require__(18);
  7571. var _pdf_scripting_manager = __w_pdfjs_require__(21);
  7572. var _pdf_single_page_viewer = __w_pdfjs_require__(23);
  7573. var _pdf_viewer = __w_pdfjs_require__(24);
  7574. var _struct_tree_layer_builder = __w_pdfjs_require__(8);
  7575. var _text_layer_builder = __w_pdfjs_require__(9);
  7576. var _xfa_layer_builder = __w_pdfjs_require__(10);
  7577. const pdfjsVersion = '3.1.81';
  7578. const pdfjsBuild = '0766898d5';
  7579. })();
  7580. /******/ return __webpack_exports__;
  7581. /******/ })()
  7582. ;
  7583. });
  7584. //# sourceMappingURL=pdf_viewer.js.map