pdf.mjs 748 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2024 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. /******/ var __webpack_modules__ = ({
  23. /***/ 9306:
  24. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  25. var isCallable = __webpack_require__(4901);
  26. var tryToString = __webpack_require__(6823);
  27. var $TypeError = TypeError;
  28. // `Assert: IsCallable(argument) is true`
  29. module.exports = function (argument) {
  30. if (isCallable(argument)) return argument;
  31. throw new $TypeError(tryToString(argument) + ' is not a function');
  32. };
  33. /***/ }),
  34. /***/ 3506:
  35. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  36. var isPossiblePrototype = __webpack_require__(3925);
  37. var $String = String;
  38. var $TypeError = TypeError;
  39. module.exports = function (argument) {
  40. if (isPossiblePrototype(argument)) return argument;
  41. throw new $TypeError("Can't set " + $String(argument) + ' as a prototype');
  42. };
  43. /***/ }),
  44. /***/ 7080:
  45. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  46. var has = (__webpack_require__(4402).has);
  47. // Perform ? RequireInternalSlot(M, [[SetData]])
  48. module.exports = function (it) {
  49. has(it);
  50. return it;
  51. };
  52. /***/ }),
  53. /***/ 679:
  54. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  55. var isPrototypeOf = __webpack_require__(1625);
  56. var $TypeError = TypeError;
  57. module.exports = function (it, Prototype) {
  58. if (isPrototypeOf(Prototype, it)) return it;
  59. throw new $TypeError('Incorrect invocation');
  60. };
  61. /***/ }),
  62. /***/ 8551:
  63. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  64. var isObject = __webpack_require__(34);
  65. var $String = String;
  66. var $TypeError = TypeError;
  67. // `Assert: Type(argument) is Object`
  68. module.exports = function (argument) {
  69. if (isObject(argument)) return argument;
  70. throw new $TypeError($String(argument) + ' is not an object');
  71. };
  72. /***/ }),
  73. /***/ 7811:
  74. /***/ ((module) => {
  75. // eslint-disable-next-line es/no-typed-arrays -- safe
  76. module.exports = typeof ArrayBuffer != 'undefined' && typeof DataView != 'undefined';
  77. /***/ }),
  78. /***/ 7394:
  79. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  80. var globalThis = __webpack_require__(4576);
  81. var uncurryThisAccessor = __webpack_require__(6706);
  82. var classof = __webpack_require__(2195);
  83. var ArrayBuffer = globalThis.ArrayBuffer;
  84. var TypeError = globalThis.TypeError;
  85. // Includes
  86. // - Perform ? RequireInternalSlot(O, [[ArrayBufferData]]).
  87. // - If IsSharedArrayBuffer(O) is true, throw a TypeError exception.
  88. module.exports = ArrayBuffer && uncurryThisAccessor(ArrayBuffer.prototype, 'byteLength', 'get') || function (O) {
  89. if (classof(O) !== 'ArrayBuffer') throw new TypeError('ArrayBuffer expected');
  90. return O.byteLength;
  91. };
  92. /***/ }),
  93. /***/ 3238:
  94. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  95. var globalThis = __webpack_require__(4576);
  96. var uncurryThis = __webpack_require__(7476);
  97. var arrayBufferByteLength = __webpack_require__(7394);
  98. var ArrayBuffer = globalThis.ArrayBuffer;
  99. var ArrayBufferPrototype = ArrayBuffer && ArrayBuffer.prototype;
  100. var slice = ArrayBufferPrototype && uncurryThis(ArrayBufferPrototype.slice);
  101. module.exports = function (O) {
  102. if (arrayBufferByteLength(O) !== 0) return false;
  103. if (!slice) return false;
  104. try {
  105. slice(O, 0, 0);
  106. return false;
  107. } catch (error) {
  108. return true;
  109. }
  110. };
  111. /***/ }),
  112. /***/ 5169:
  113. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  114. var isDetached = __webpack_require__(3238);
  115. var $TypeError = TypeError;
  116. module.exports = function (it) {
  117. if (isDetached(it)) throw new $TypeError('ArrayBuffer is detached');
  118. return it;
  119. };
  120. /***/ }),
  121. /***/ 5636:
  122. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  123. var globalThis = __webpack_require__(4576);
  124. var uncurryThis = __webpack_require__(9504);
  125. var uncurryThisAccessor = __webpack_require__(6706);
  126. var toIndex = __webpack_require__(7696);
  127. var notDetached = __webpack_require__(5169);
  128. var arrayBufferByteLength = __webpack_require__(7394);
  129. var detachTransferable = __webpack_require__(4483);
  130. var PROPER_STRUCTURED_CLONE_TRANSFER = __webpack_require__(1548);
  131. var structuredClone = globalThis.structuredClone;
  132. var ArrayBuffer = globalThis.ArrayBuffer;
  133. var DataView = globalThis.DataView;
  134. var min = Math.min;
  135. var ArrayBufferPrototype = ArrayBuffer.prototype;
  136. var DataViewPrototype = DataView.prototype;
  137. var slice = uncurryThis(ArrayBufferPrototype.slice);
  138. var isResizable = uncurryThisAccessor(ArrayBufferPrototype, 'resizable', 'get');
  139. var maxByteLength = uncurryThisAccessor(ArrayBufferPrototype, 'maxByteLength', 'get');
  140. var getInt8 = uncurryThis(DataViewPrototype.getInt8);
  141. var setInt8 = uncurryThis(DataViewPrototype.setInt8);
  142. module.exports = (PROPER_STRUCTURED_CLONE_TRANSFER || detachTransferable) && function (arrayBuffer, newLength, preserveResizability) {
  143. var byteLength = arrayBufferByteLength(arrayBuffer);
  144. var newByteLength = newLength === undefined ? byteLength : toIndex(newLength);
  145. var fixedLength = !isResizable || !isResizable(arrayBuffer);
  146. var newBuffer;
  147. notDetached(arrayBuffer);
  148. if (PROPER_STRUCTURED_CLONE_TRANSFER) {
  149. arrayBuffer = structuredClone(arrayBuffer, { transfer: [arrayBuffer] });
  150. if (byteLength === newByteLength && (preserveResizability || fixedLength)) return arrayBuffer;
  151. }
  152. if (byteLength >= newByteLength && (!preserveResizability || fixedLength)) {
  153. newBuffer = slice(arrayBuffer, 0, newByteLength);
  154. } else {
  155. var options = preserveResizability && !fixedLength && maxByteLength ? { maxByteLength: maxByteLength(arrayBuffer) } : undefined;
  156. newBuffer = new ArrayBuffer(newByteLength, options);
  157. var a = new DataView(arrayBuffer);
  158. var b = new DataView(newBuffer);
  159. var copyLength = min(newByteLength, byteLength);
  160. for (var i = 0; i < copyLength; i++) setInt8(b, i, getInt8(a, i));
  161. }
  162. if (!PROPER_STRUCTURED_CLONE_TRANSFER) detachTransferable(arrayBuffer);
  163. return newBuffer;
  164. };
  165. /***/ }),
  166. /***/ 4644:
  167. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  168. var NATIVE_ARRAY_BUFFER = __webpack_require__(7811);
  169. var DESCRIPTORS = __webpack_require__(3724);
  170. var globalThis = __webpack_require__(4576);
  171. var isCallable = __webpack_require__(4901);
  172. var isObject = __webpack_require__(34);
  173. var hasOwn = __webpack_require__(9297);
  174. var classof = __webpack_require__(6955);
  175. var tryToString = __webpack_require__(6823);
  176. var createNonEnumerableProperty = __webpack_require__(6699);
  177. var defineBuiltIn = __webpack_require__(6840);
  178. var defineBuiltInAccessor = __webpack_require__(2106);
  179. var isPrototypeOf = __webpack_require__(1625);
  180. var getPrototypeOf = __webpack_require__(2787);
  181. var setPrototypeOf = __webpack_require__(2967);
  182. var wellKnownSymbol = __webpack_require__(8227);
  183. var uid = __webpack_require__(3392);
  184. var InternalStateModule = __webpack_require__(1181);
  185. var enforceInternalState = InternalStateModule.enforce;
  186. var getInternalState = InternalStateModule.get;
  187. var Int8Array = globalThis.Int8Array;
  188. var Int8ArrayPrototype = Int8Array && Int8Array.prototype;
  189. var Uint8ClampedArray = globalThis.Uint8ClampedArray;
  190. var Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype;
  191. var TypedArray = Int8Array && getPrototypeOf(Int8Array);
  192. var TypedArrayPrototype = Int8ArrayPrototype && getPrototypeOf(Int8ArrayPrototype);
  193. var ObjectPrototype = Object.prototype;
  194. var TypeError = globalThis.TypeError;
  195. var TO_STRING_TAG = wellKnownSymbol('toStringTag');
  196. var TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG');
  197. var TYPED_ARRAY_CONSTRUCTOR = 'TypedArrayConstructor';
  198. // Fixing native typed arrays in Opera Presto crashes the browser, see #595
  199. var NATIVE_ARRAY_BUFFER_VIEWS = NATIVE_ARRAY_BUFFER && !!setPrototypeOf && classof(globalThis.opera) !== 'Opera';
  200. var TYPED_ARRAY_TAG_REQUIRED = false;
  201. var NAME, Constructor, Prototype;
  202. var TypedArrayConstructorsList = {
  203. Int8Array: 1,
  204. Uint8Array: 1,
  205. Uint8ClampedArray: 1,
  206. Int16Array: 2,
  207. Uint16Array: 2,
  208. Int32Array: 4,
  209. Uint32Array: 4,
  210. Float32Array: 4,
  211. Float64Array: 8
  212. };
  213. var BigIntArrayConstructorsList = {
  214. BigInt64Array: 8,
  215. BigUint64Array: 8
  216. };
  217. var isView = function isView(it) {
  218. if (!isObject(it)) return false;
  219. var klass = classof(it);
  220. return klass === 'DataView'
  221. || hasOwn(TypedArrayConstructorsList, klass)
  222. || hasOwn(BigIntArrayConstructorsList, klass);
  223. };
  224. var getTypedArrayConstructor = function (it) {
  225. var proto = getPrototypeOf(it);
  226. if (!isObject(proto)) return;
  227. var state = getInternalState(proto);
  228. return (state && hasOwn(state, TYPED_ARRAY_CONSTRUCTOR)) ? state[TYPED_ARRAY_CONSTRUCTOR] : getTypedArrayConstructor(proto);
  229. };
  230. var isTypedArray = function (it) {
  231. if (!isObject(it)) return false;
  232. var klass = classof(it);
  233. return hasOwn(TypedArrayConstructorsList, klass)
  234. || hasOwn(BigIntArrayConstructorsList, klass);
  235. };
  236. var aTypedArray = function (it) {
  237. if (isTypedArray(it)) return it;
  238. throw new TypeError('Target is not a typed array');
  239. };
  240. var aTypedArrayConstructor = function (C) {
  241. if (isCallable(C) && (!setPrototypeOf || isPrototypeOf(TypedArray, C))) return C;
  242. throw new TypeError(tryToString(C) + ' is not a typed array constructor');
  243. };
  244. var exportTypedArrayMethod = function (KEY, property, forced, options) {
  245. if (!DESCRIPTORS) return;
  246. if (forced) for (var ARRAY in TypedArrayConstructorsList) {
  247. var TypedArrayConstructor = globalThis[ARRAY];
  248. if (TypedArrayConstructor && hasOwn(TypedArrayConstructor.prototype, KEY)) try {
  249. delete TypedArrayConstructor.prototype[KEY];
  250. } catch (error) {
  251. // old WebKit bug - some methods are non-configurable
  252. try {
  253. TypedArrayConstructor.prototype[KEY] = property;
  254. } catch (error2) { /* empty */ }
  255. }
  256. }
  257. if (!TypedArrayPrototype[KEY] || forced) {
  258. defineBuiltIn(TypedArrayPrototype, KEY, forced ? property
  259. : NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property, options);
  260. }
  261. };
  262. var exportTypedArrayStaticMethod = function (KEY, property, forced) {
  263. var ARRAY, TypedArrayConstructor;
  264. if (!DESCRIPTORS) return;
  265. if (setPrototypeOf) {
  266. if (forced) for (ARRAY in TypedArrayConstructorsList) {
  267. TypedArrayConstructor = globalThis[ARRAY];
  268. if (TypedArrayConstructor && hasOwn(TypedArrayConstructor, KEY)) try {
  269. delete TypedArrayConstructor[KEY];
  270. } catch (error) { /* empty */ }
  271. }
  272. if (!TypedArray[KEY] || forced) {
  273. // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable
  274. try {
  275. return defineBuiltIn(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && TypedArray[KEY] || property);
  276. } catch (error) { /* empty */ }
  277. } else return;
  278. }
  279. for (ARRAY in TypedArrayConstructorsList) {
  280. TypedArrayConstructor = globalThis[ARRAY];
  281. if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) {
  282. defineBuiltIn(TypedArrayConstructor, KEY, property);
  283. }
  284. }
  285. };
  286. for (NAME in TypedArrayConstructorsList) {
  287. Constructor = globalThis[NAME];
  288. Prototype = Constructor && Constructor.prototype;
  289. if (Prototype) enforceInternalState(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor;
  290. else NATIVE_ARRAY_BUFFER_VIEWS = false;
  291. }
  292. for (NAME in BigIntArrayConstructorsList) {
  293. Constructor = globalThis[NAME];
  294. Prototype = Constructor && Constructor.prototype;
  295. if (Prototype) enforceInternalState(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor;
  296. }
  297. // WebKit bug - typed arrays constructors prototype is Object.prototype
  298. if (!NATIVE_ARRAY_BUFFER_VIEWS || !isCallable(TypedArray) || TypedArray === Function.prototype) {
  299. // eslint-disable-next-line no-shadow -- safe
  300. TypedArray = function TypedArray() {
  301. throw new TypeError('Incorrect invocation');
  302. };
  303. if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {
  304. if (globalThis[NAME]) setPrototypeOf(globalThis[NAME], TypedArray);
  305. }
  306. }
  307. if (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype) {
  308. TypedArrayPrototype = TypedArray.prototype;
  309. if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {
  310. if (globalThis[NAME]) setPrototypeOf(globalThis[NAME].prototype, TypedArrayPrototype);
  311. }
  312. }
  313. // WebKit bug - one more object in Uint8ClampedArray prototype chain
  314. if (NATIVE_ARRAY_BUFFER_VIEWS && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) {
  315. setPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype);
  316. }
  317. if (DESCRIPTORS && !hasOwn(TypedArrayPrototype, TO_STRING_TAG)) {
  318. TYPED_ARRAY_TAG_REQUIRED = true;
  319. defineBuiltInAccessor(TypedArrayPrototype, TO_STRING_TAG, {
  320. configurable: true,
  321. get: function () {
  322. return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined;
  323. }
  324. });
  325. for (NAME in TypedArrayConstructorsList) if (globalThis[NAME]) {
  326. createNonEnumerableProperty(globalThis[NAME], TYPED_ARRAY_TAG, NAME);
  327. }
  328. }
  329. module.exports = {
  330. NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS,
  331. TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQUIRED && TYPED_ARRAY_TAG,
  332. aTypedArray: aTypedArray,
  333. aTypedArrayConstructor: aTypedArrayConstructor,
  334. exportTypedArrayMethod: exportTypedArrayMethod,
  335. exportTypedArrayStaticMethod: exportTypedArrayStaticMethod,
  336. getTypedArrayConstructor: getTypedArrayConstructor,
  337. isView: isView,
  338. isTypedArray: isTypedArray,
  339. TypedArray: TypedArray,
  340. TypedArrayPrototype: TypedArrayPrototype
  341. };
  342. /***/ }),
  343. /***/ 5370:
  344. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  345. var lengthOfArrayLike = __webpack_require__(6198);
  346. module.exports = function (Constructor, list, $length) {
  347. var index = 0;
  348. var length = arguments.length > 2 ? $length : lengthOfArrayLike(list);
  349. var result = new Constructor(length);
  350. while (length > index) result[index] = list[index++];
  351. return result;
  352. };
  353. /***/ }),
  354. /***/ 9617:
  355. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  356. var toIndexedObject = __webpack_require__(5397);
  357. var toAbsoluteIndex = __webpack_require__(5610);
  358. var lengthOfArrayLike = __webpack_require__(6198);
  359. // `Array.prototype.{ indexOf, includes }` methods implementation
  360. var createMethod = function (IS_INCLUDES) {
  361. return function ($this, el, fromIndex) {
  362. var O = toIndexedObject($this);
  363. var length = lengthOfArrayLike(O);
  364. if (length === 0) return !IS_INCLUDES && -1;
  365. var index = toAbsoluteIndex(fromIndex, length);
  366. var value;
  367. // Array#includes uses SameValueZero equality algorithm
  368. // eslint-disable-next-line no-self-compare -- NaN check
  369. if (IS_INCLUDES && el !== el) while (length > index) {
  370. value = O[index++];
  371. // eslint-disable-next-line no-self-compare -- NaN check
  372. if (value !== value) return true;
  373. // Array#indexOf ignores holes, Array#includes - not
  374. } else for (;length > index; index++) {
  375. if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
  376. } return !IS_INCLUDES && -1;
  377. };
  378. };
  379. module.exports = {
  380. // `Array.prototype.includes` method
  381. // https://tc39.es/ecma262/#sec-array.prototype.includes
  382. includes: createMethod(true),
  383. // `Array.prototype.indexOf` method
  384. // https://tc39.es/ecma262/#sec-array.prototype.indexof
  385. indexOf: createMethod(false)
  386. };
  387. /***/ }),
  388. /***/ 4527:
  389. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  390. var DESCRIPTORS = __webpack_require__(3724);
  391. var isArray = __webpack_require__(4376);
  392. var $TypeError = TypeError;
  393. // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
  394. var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  395. // Safari < 13 does not throw an error in this case
  396. var SILENT_ON_NON_WRITABLE_LENGTH_SET = DESCRIPTORS && !function () {
  397. // makes no sense without proper strict mode support
  398. if (this !== undefined) return true;
  399. try {
  400. // eslint-disable-next-line es/no-object-defineproperty -- safe
  401. Object.defineProperty([], 'length', { writable: false }).length = 1;
  402. } catch (error) {
  403. return error instanceof TypeError;
  404. }
  405. }();
  406. module.exports = SILENT_ON_NON_WRITABLE_LENGTH_SET ? function (O, length) {
  407. if (isArray(O) && !getOwnPropertyDescriptor(O, 'length').writable) {
  408. throw new $TypeError('Cannot set read only .length');
  409. } return O.length = length;
  410. } : function (O, length) {
  411. return O.length = length;
  412. };
  413. /***/ }),
  414. /***/ 7628:
  415. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  416. var lengthOfArrayLike = __webpack_require__(6198);
  417. // https://tc39.es/proposal-change-array-by-copy/#sec-array.prototype.toReversed
  418. // https://tc39.es/proposal-change-array-by-copy/#sec-%typedarray%.prototype.toReversed
  419. module.exports = function (O, C) {
  420. var len = lengthOfArrayLike(O);
  421. var A = new C(len);
  422. var k = 0;
  423. for (; k < len; k++) A[k] = O[len - k - 1];
  424. return A;
  425. };
  426. /***/ }),
  427. /***/ 9928:
  428. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  429. var lengthOfArrayLike = __webpack_require__(6198);
  430. var toIntegerOrInfinity = __webpack_require__(1291);
  431. var $RangeError = RangeError;
  432. // https://tc39.es/proposal-change-array-by-copy/#sec-array.prototype.with
  433. // https://tc39.es/proposal-change-array-by-copy/#sec-%typedarray%.prototype.with
  434. module.exports = function (O, C, index, value) {
  435. var len = lengthOfArrayLike(O);
  436. var relativeIndex = toIntegerOrInfinity(index);
  437. var actualIndex = relativeIndex < 0 ? len + relativeIndex : relativeIndex;
  438. if (actualIndex >= len || actualIndex < 0) throw new $RangeError('Incorrect index');
  439. var A = new C(len);
  440. var k = 0;
  441. for (; k < len; k++) A[k] = k === actualIndex ? value : O[k];
  442. return A;
  443. };
  444. /***/ }),
  445. /***/ 6319:
  446. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  447. var anObject = __webpack_require__(8551);
  448. var iteratorClose = __webpack_require__(9539);
  449. // call something on iterator step with safe closing on error
  450. module.exports = function (iterator, fn, value, ENTRIES) {
  451. try {
  452. return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value);
  453. } catch (error) {
  454. iteratorClose(iterator, 'throw', error);
  455. }
  456. };
  457. /***/ }),
  458. /***/ 2195:
  459. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  460. var uncurryThis = __webpack_require__(9504);
  461. var toString = uncurryThis({}.toString);
  462. var stringSlice = uncurryThis(''.slice);
  463. module.exports = function (it) {
  464. return stringSlice(toString(it), 8, -1);
  465. };
  466. /***/ }),
  467. /***/ 6955:
  468. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  469. var TO_STRING_TAG_SUPPORT = __webpack_require__(2140);
  470. var isCallable = __webpack_require__(4901);
  471. var classofRaw = __webpack_require__(2195);
  472. var wellKnownSymbol = __webpack_require__(8227);
  473. var TO_STRING_TAG = wellKnownSymbol('toStringTag');
  474. var $Object = Object;
  475. // ES3 wrong here
  476. var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) === 'Arguments';
  477. // fallback for IE11 Script Access Denied error
  478. var tryGet = function (it, key) {
  479. try {
  480. return it[key];
  481. } catch (error) { /* empty */ }
  482. };
  483. // getting tag from ES6+ `Object.prototype.toString`
  484. module.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) {
  485. var O, tag, result;
  486. return it === undefined ? 'Undefined' : it === null ? 'Null'
  487. // @@toStringTag case
  488. : typeof (tag = tryGet(O = $Object(it), TO_STRING_TAG)) == 'string' ? tag
  489. // builtinTag case
  490. : CORRECT_ARGUMENTS ? classofRaw(O)
  491. // ES3 arguments fallback
  492. : (result = classofRaw(O)) === 'Object' && isCallable(O.callee) ? 'Arguments' : result;
  493. };
  494. /***/ }),
  495. /***/ 7740:
  496. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  497. var hasOwn = __webpack_require__(9297);
  498. var ownKeys = __webpack_require__(5031);
  499. var getOwnPropertyDescriptorModule = __webpack_require__(7347);
  500. var definePropertyModule = __webpack_require__(4913);
  501. module.exports = function (target, source, exceptions) {
  502. var keys = ownKeys(source);
  503. var defineProperty = definePropertyModule.f;
  504. var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
  505. for (var i = 0; i < keys.length; i++) {
  506. var key = keys[i];
  507. if (!hasOwn(target, key) && !(exceptions && hasOwn(exceptions, key))) {
  508. defineProperty(target, key, getOwnPropertyDescriptor(source, key));
  509. }
  510. }
  511. };
  512. /***/ }),
  513. /***/ 2211:
  514. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  515. var fails = __webpack_require__(9039);
  516. module.exports = !fails(function () {
  517. function F() { /* empty */ }
  518. F.prototype.constructor = null;
  519. // eslint-disable-next-line es/no-object-getprototypeof -- required for testing
  520. return Object.getPrototypeOf(new F()) !== F.prototype;
  521. });
  522. /***/ }),
  523. /***/ 2529:
  524. /***/ ((module) => {
  525. // `CreateIterResultObject` abstract operation
  526. // https://tc39.es/ecma262/#sec-createiterresultobject
  527. module.exports = function (value, done) {
  528. return { value: value, done: done };
  529. };
  530. /***/ }),
  531. /***/ 6699:
  532. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  533. var DESCRIPTORS = __webpack_require__(3724);
  534. var definePropertyModule = __webpack_require__(4913);
  535. var createPropertyDescriptor = __webpack_require__(6980);
  536. module.exports = DESCRIPTORS ? function (object, key, value) {
  537. return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));
  538. } : function (object, key, value) {
  539. object[key] = value;
  540. return object;
  541. };
  542. /***/ }),
  543. /***/ 6980:
  544. /***/ ((module) => {
  545. module.exports = function (bitmap, value) {
  546. return {
  547. enumerable: !(bitmap & 1),
  548. configurable: !(bitmap & 2),
  549. writable: !(bitmap & 4),
  550. value: value
  551. };
  552. };
  553. /***/ }),
  554. /***/ 4659:
  555. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  556. var DESCRIPTORS = __webpack_require__(3724);
  557. var definePropertyModule = __webpack_require__(4913);
  558. var createPropertyDescriptor = __webpack_require__(6980);
  559. module.exports = function (object, key, value) {
  560. if (DESCRIPTORS) definePropertyModule.f(object, key, createPropertyDescriptor(0, value));
  561. else object[key] = value;
  562. };
  563. /***/ }),
  564. /***/ 2106:
  565. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  566. var makeBuiltIn = __webpack_require__(283);
  567. var defineProperty = __webpack_require__(4913);
  568. module.exports = function (target, name, descriptor) {
  569. if (descriptor.get) makeBuiltIn(descriptor.get, name, { getter: true });
  570. if (descriptor.set) makeBuiltIn(descriptor.set, name, { setter: true });
  571. return defineProperty.f(target, name, descriptor);
  572. };
  573. /***/ }),
  574. /***/ 6840:
  575. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  576. var isCallable = __webpack_require__(4901);
  577. var definePropertyModule = __webpack_require__(4913);
  578. var makeBuiltIn = __webpack_require__(283);
  579. var defineGlobalProperty = __webpack_require__(9433);
  580. module.exports = function (O, key, value, options) {
  581. if (!options) options = {};
  582. var simple = options.enumerable;
  583. var name = options.name !== undefined ? options.name : key;
  584. if (isCallable(value)) makeBuiltIn(value, name, options);
  585. if (options.global) {
  586. if (simple) O[key] = value;
  587. else defineGlobalProperty(key, value);
  588. } else {
  589. try {
  590. if (!options.unsafe) delete O[key];
  591. else if (O[key]) simple = true;
  592. } catch (error) { /* empty */ }
  593. if (simple) O[key] = value;
  594. else definePropertyModule.f(O, key, {
  595. value: value,
  596. enumerable: false,
  597. configurable: !options.nonConfigurable,
  598. writable: !options.nonWritable
  599. });
  600. } return O;
  601. };
  602. /***/ }),
  603. /***/ 6279:
  604. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  605. var defineBuiltIn = __webpack_require__(6840);
  606. module.exports = function (target, src, options) {
  607. for (var key in src) defineBuiltIn(target, key, src[key], options);
  608. return target;
  609. };
  610. /***/ }),
  611. /***/ 9433:
  612. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  613. var globalThis = __webpack_require__(4576);
  614. // eslint-disable-next-line es/no-object-defineproperty -- safe
  615. var defineProperty = Object.defineProperty;
  616. module.exports = function (key, value) {
  617. try {
  618. defineProperty(globalThis, key, { value: value, configurable: true, writable: true });
  619. } catch (error) {
  620. globalThis[key] = value;
  621. } return value;
  622. };
  623. /***/ }),
  624. /***/ 3724:
  625. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  626. var fails = __webpack_require__(9039);
  627. // Detect IE8's incomplete defineProperty implementation
  628. module.exports = !fails(function () {
  629. // eslint-disable-next-line es/no-object-defineproperty -- required for testing
  630. return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] !== 7;
  631. });
  632. /***/ }),
  633. /***/ 4483:
  634. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  635. var globalThis = __webpack_require__(4576);
  636. var getBuiltInNodeModule = __webpack_require__(9429);
  637. var PROPER_STRUCTURED_CLONE_TRANSFER = __webpack_require__(1548);
  638. var structuredClone = globalThis.structuredClone;
  639. var $ArrayBuffer = globalThis.ArrayBuffer;
  640. var $MessageChannel = globalThis.MessageChannel;
  641. var detach = false;
  642. var WorkerThreads, channel, buffer, $detach;
  643. if (PROPER_STRUCTURED_CLONE_TRANSFER) {
  644. detach = function (transferable) {
  645. structuredClone(transferable, { transfer: [transferable] });
  646. };
  647. } else if ($ArrayBuffer) try {
  648. if (!$MessageChannel) {
  649. WorkerThreads = getBuiltInNodeModule('worker_threads');
  650. if (WorkerThreads) $MessageChannel = WorkerThreads.MessageChannel;
  651. }
  652. if ($MessageChannel) {
  653. channel = new $MessageChannel();
  654. buffer = new $ArrayBuffer(2);
  655. $detach = function (transferable) {
  656. channel.port1.postMessage(null, [transferable]);
  657. };
  658. if (buffer.byteLength === 2) {
  659. $detach(buffer);
  660. if (buffer.byteLength === 0) detach = $detach;
  661. }
  662. }
  663. } catch (error) { /* empty */ }
  664. module.exports = detach;
  665. /***/ }),
  666. /***/ 4055:
  667. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  668. var globalThis = __webpack_require__(4576);
  669. var isObject = __webpack_require__(34);
  670. var document = globalThis.document;
  671. // typeof document.createElement is 'object' in old IE
  672. var EXISTS = isObject(document) && isObject(document.createElement);
  673. module.exports = function (it) {
  674. return EXISTS ? document.createElement(it) : {};
  675. };
  676. /***/ }),
  677. /***/ 6837:
  678. /***/ ((module) => {
  679. var $TypeError = TypeError;
  680. var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; // 2 ** 53 - 1 == 9007199254740991
  681. module.exports = function (it) {
  682. if (it > MAX_SAFE_INTEGER) throw $TypeError('Maximum allowed index exceeded');
  683. return it;
  684. };
  685. /***/ }),
  686. /***/ 5002:
  687. /***/ ((module) => {
  688. module.exports = {
  689. IndexSizeError: { s: 'INDEX_SIZE_ERR', c: 1, m: 1 },
  690. DOMStringSizeError: { s: 'DOMSTRING_SIZE_ERR', c: 2, m: 0 },
  691. HierarchyRequestError: { s: 'HIERARCHY_REQUEST_ERR', c: 3, m: 1 },
  692. WrongDocumentError: { s: 'WRONG_DOCUMENT_ERR', c: 4, m: 1 },
  693. InvalidCharacterError: { s: 'INVALID_CHARACTER_ERR', c: 5, m: 1 },
  694. NoDataAllowedError: { s: 'NO_DATA_ALLOWED_ERR', c: 6, m: 0 },
  695. NoModificationAllowedError: { s: 'NO_MODIFICATION_ALLOWED_ERR', c: 7, m: 1 },
  696. NotFoundError: { s: 'NOT_FOUND_ERR', c: 8, m: 1 },
  697. NotSupportedError: { s: 'NOT_SUPPORTED_ERR', c: 9, m: 1 },
  698. InUseAttributeError: { s: 'INUSE_ATTRIBUTE_ERR', c: 10, m: 1 },
  699. InvalidStateError: { s: 'INVALID_STATE_ERR', c: 11, m: 1 },
  700. SyntaxError: { s: 'SYNTAX_ERR', c: 12, m: 1 },
  701. InvalidModificationError: { s: 'INVALID_MODIFICATION_ERR', c: 13, m: 1 },
  702. NamespaceError: { s: 'NAMESPACE_ERR', c: 14, m: 1 },
  703. InvalidAccessError: { s: 'INVALID_ACCESS_ERR', c: 15, m: 1 },
  704. ValidationError: { s: 'VALIDATION_ERR', c: 16, m: 0 },
  705. TypeMismatchError: { s: 'TYPE_MISMATCH_ERR', c: 17, m: 1 },
  706. SecurityError: { s: 'SECURITY_ERR', c: 18, m: 1 },
  707. NetworkError: { s: 'NETWORK_ERR', c: 19, m: 1 },
  708. AbortError: { s: 'ABORT_ERR', c: 20, m: 1 },
  709. URLMismatchError: { s: 'URL_MISMATCH_ERR', c: 21, m: 1 },
  710. QuotaExceededError: { s: 'QUOTA_EXCEEDED_ERR', c: 22, m: 1 },
  711. TimeoutError: { s: 'TIMEOUT_ERR', c: 23, m: 1 },
  712. InvalidNodeTypeError: { s: 'INVALID_NODE_TYPE_ERR', c: 24, m: 1 },
  713. DataCloneError: { s: 'DATA_CLONE_ERR', c: 25, m: 1 }
  714. };
  715. /***/ }),
  716. /***/ 8727:
  717. /***/ ((module) => {
  718. // IE8- don't enum bug keys
  719. module.exports = [
  720. 'constructor',
  721. 'hasOwnProperty',
  722. 'isPrototypeOf',
  723. 'propertyIsEnumerable',
  724. 'toLocaleString',
  725. 'toString',
  726. 'valueOf'
  727. ];
  728. /***/ }),
  729. /***/ 6193:
  730. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  731. var ENVIRONMENT = __webpack_require__(4215);
  732. module.exports = ENVIRONMENT === 'NODE';
  733. /***/ }),
  734. /***/ 2839:
  735. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  736. var globalThis = __webpack_require__(4576);
  737. var navigator = globalThis.navigator;
  738. var userAgent = navigator && navigator.userAgent;
  739. module.exports = userAgent ? String(userAgent) : '';
  740. /***/ }),
  741. /***/ 9519:
  742. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  743. var globalThis = __webpack_require__(4576);
  744. var userAgent = __webpack_require__(2839);
  745. var process = globalThis.process;
  746. var Deno = globalThis.Deno;
  747. var versions = process && process.versions || Deno && Deno.version;
  748. var v8 = versions && versions.v8;
  749. var match, version;
  750. if (v8) {
  751. match = v8.split('.');
  752. // in old Chrome, versions of V8 isn't V8 = Chrome / 10
  753. // but their correct versions are not interesting for us
  754. version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]);
  755. }
  756. // BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0`
  757. // so check `userAgent` even if `.v8` exists, but 0
  758. if (!version && userAgent) {
  759. match = userAgent.match(/Edge\/(\d+)/);
  760. if (!match || match[1] >= 74) {
  761. match = userAgent.match(/Chrome\/(\d+)/);
  762. if (match) version = +match[1];
  763. }
  764. }
  765. module.exports = version;
  766. /***/ }),
  767. /***/ 4215:
  768. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  769. /* global Bun, Deno -- detection */
  770. var globalThis = __webpack_require__(4576);
  771. var userAgent = __webpack_require__(2839);
  772. var classof = __webpack_require__(2195);
  773. var userAgentStartsWith = function (string) {
  774. return userAgent.slice(0, string.length) === string;
  775. };
  776. module.exports = (function () {
  777. if (userAgentStartsWith('Bun/')) return 'BUN';
  778. if (userAgentStartsWith('Cloudflare-Workers')) return 'CLOUDFLARE';
  779. if (userAgentStartsWith('Deno/')) return 'DENO';
  780. if (userAgentStartsWith('Node.js/')) return 'NODE';
  781. if (globalThis.Bun && typeof Bun.version == 'string') return 'BUN';
  782. if (globalThis.Deno && typeof Deno.version == 'object') return 'DENO';
  783. if (classof(globalThis.process) === 'process') return 'NODE';
  784. if (globalThis.window && globalThis.document) return 'BROWSER';
  785. return 'REST';
  786. })();
  787. /***/ }),
  788. /***/ 8574:
  789. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  790. var uncurryThis = __webpack_require__(9504);
  791. var $Error = Error;
  792. var replace = uncurryThis(''.replace);
  793. var TEST = (function (arg) { return String(new $Error(arg).stack); })('zxcasd');
  794. // eslint-disable-next-line redos/no-vulnerable -- safe
  795. var V8_OR_CHAKRA_STACK_ENTRY = /\n\s*at [^:]*:[^\n]*/;
  796. var IS_V8_OR_CHAKRA_STACK = V8_OR_CHAKRA_STACK_ENTRY.test(TEST);
  797. module.exports = function (stack, dropEntries) {
  798. if (IS_V8_OR_CHAKRA_STACK && typeof stack == 'string' && !$Error.prepareStackTrace) {
  799. while (dropEntries--) stack = replace(stack, V8_OR_CHAKRA_STACK_ENTRY, '');
  800. } return stack;
  801. };
  802. /***/ }),
  803. /***/ 6518:
  804. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  805. var globalThis = __webpack_require__(4576);
  806. var getOwnPropertyDescriptor = (__webpack_require__(7347).f);
  807. var createNonEnumerableProperty = __webpack_require__(6699);
  808. var defineBuiltIn = __webpack_require__(6840);
  809. var defineGlobalProperty = __webpack_require__(9433);
  810. var copyConstructorProperties = __webpack_require__(7740);
  811. var isForced = __webpack_require__(2796);
  812. /*
  813. options.target - name of the target object
  814. options.global - target is the global object
  815. options.stat - export as static methods of target
  816. options.proto - export as prototype methods of target
  817. options.real - real prototype method for the `pure` version
  818. options.forced - export even if the native feature is available
  819. options.bind - bind methods to the target, required for the `pure` version
  820. options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
  821. options.unsafe - use the simple assignment of property instead of delete + defineProperty
  822. options.sham - add a flag to not completely full polyfills
  823. options.enumerable - export as enumerable property
  824. options.dontCallGetSet - prevent calling a getter on target
  825. options.name - the .name of the function if it does not match the key
  826. */
  827. module.exports = function (options, source) {
  828. var TARGET = options.target;
  829. var GLOBAL = options.global;
  830. var STATIC = options.stat;
  831. var FORCED, target, key, targetProperty, sourceProperty, descriptor;
  832. if (GLOBAL) {
  833. target = globalThis;
  834. } else if (STATIC) {
  835. target = globalThis[TARGET] || defineGlobalProperty(TARGET, {});
  836. } else {
  837. target = globalThis[TARGET] && globalThis[TARGET].prototype;
  838. }
  839. if (target) for (key in source) {
  840. sourceProperty = source[key];
  841. if (options.dontCallGetSet) {
  842. descriptor = getOwnPropertyDescriptor(target, key);
  843. targetProperty = descriptor && descriptor.value;
  844. } else targetProperty = target[key];
  845. FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
  846. // contained in target
  847. if (!FORCED && targetProperty !== undefined) {
  848. if (typeof sourceProperty == typeof targetProperty) continue;
  849. copyConstructorProperties(sourceProperty, targetProperty);
  850. }
  851. // add a flag to not completely full polyfills
  852. if (options.sham || (targetProperty && targetProperty.sham)) {
  853. createNonEnumerableProperty(sourceProperty, 'sham', true);
  854. }
  855. defineBuiltIn(target, key, sourceProperty, options);
  856. }
  857. };
  858. /***/ }),
  859. /***/ 9039:
  860. /***/ ((module) => {
  861. module.exports = function (exec) {
  862. try {
  863. return !!exec();
  864. } catch (error) {
  865. return true;
  866. }
  867. };
  868. /***/ }),
  869. /***/ 6080:
  870. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  871. var uncurryThis = __webpack_require__(7476);
  872. var aCallable = __webpack_require__(9306);
  873. var NATIVE_BIND = __webpack_require__(616);
  874. var bind = uncurryThis(uncurryThis.bind);
  875. // optional / simple context binding
  876. module.exports = function (fn, that) {
  877. aCallable(fn);
  878. return that === undefined ? fn : NATIVE_BIND ? bind(fn, that) : function (/* ...args */) {
  879. return fn.apply(that, arguments);
  880. };
  881. };
  882. /***/ }),
  883. /***/ 616:
  884. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  885. var fails = __webpack_require__(9039);
  886. module.exports = !fails(function () {
  887. // eslint-disable-next-line es/no-function-prototype-bind -- safe
  888. var test = (function () { /* empty */ }).bind();
  889. // eslint-disable-next-line no-prototype-builtins -- safe
  890. return typeof test != 'function' || test.hasOwnProperty('prototype');
  891. });
  892. /***/ }),
  893. /***/ 9565:
  894. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  895. var NATIVE_BIND = __webpack_require__(616);
  896. var call = Function.prototype.call;
  897. module.exports = NATIVE_BIND ? call.bind(call) : function () {
  898. return call.apply(call, arguments);
  899. };
  900. /***/ }),
  901. /***/ 350:
  902. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  903. var DESCRIPTORS = __webpack_require__(3724);
  904. var hasOwn = __webpack_require__(9297);
  905. var FunctionPrototype = Function.prototype;
  906. // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
  907. var getDescriptor = DESCRIPTORS && Object.getOwnPropertyDescriptor;
  908. var EXISTS = hasOwn(FunctionPrototype, 'name');
  909. // additional protection from minified / mangled / dropped function names
  910. var PROPER = EXISTS && (function something() { /* empty */ }).name === 'something';
  911. var CONFIGURABLE = EXISTS && (!DESCRIPTORS || (DESCRIPTORS && getDescriptor(FunctionPrototype, 'name').configurable));
  912. module.exports = {
  913. EXISTS: EXISTS,
  914. PROPER: PROPER,
  915. CONFIGURABLE: CONFIGURABLE
  916. };
  917. /***/ }),
  918. /***/ 6706:
  919. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  920. var uncurryThis = __webpack_require__(9504);
  921. var aCallable = __webpack_require__(9306);
  922. module.exports = function (object, key, method) {
  923. try {
  924. // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
  925. return uncurryThis(aCallable(Object.getOwnPropertyDescriptor(object, key)[method]));
  926. } catch (error) { /* empty */ }
  927. };
  928. /***/ }),
  929. /***/ 7476:
  930. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  931. var classofRaw = __webpack_require__(2195);
  932. var uncurryThis = __webpack_require__(9504);
  933. module.exports = function (fn) {
  934. // Nashorn bug:
  935. // https://github.com/zloirock/core-js/issues/1128
  936. // https://github.com/zloirock/core-js/issues/1130
  937. if (classofRaw(fn) === 'Function') return uncurryThis(fn);
  938. };
  939. /***/ }),
  940. /***/ 9504:
  941. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  942. var NATIVE_BIND = __webpack_require__(616);
  943. var FunctionPrototype = Function.prototype;
  944. var call = FunctionPrototype.call;
  945. var uncurryThisWithBind = NATIVE_BIND && FunctionPrototype.bind.bind(call, call);
  946. module.exports = NATIVE_BIND ? uncurryThisWithBind : function (fn) {
  947. return function () {
  948. return call.apply(fn, arguments);
  949. };
  950. };
  951. /***/ }),
  952. /***/ 9429:
  953. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  954. var globalThis = __webpack_require__(4576);
  955. var IS_NODE = __webpack_require__(6193);
  956. module.exports = function (name) {
  957. if (IS_NODE) {
  958. try {
  959. return globalThis.process.getBuiltinModule(name);
  960. } catch (error) { /* empty */ }
  961. try {
  962. // eslint-disable-next-line no-new-func -- safe
  963. return Function('return require("' + name + '")')();
  964. } catch (error) { /* empty */ }
  965. }
  966. };
  967. /***/ }),
  968. /***/ 7751:
  969. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  970. var globalThis = __webpack_require__(4576);
  971. var isCallable = __webpack_require__(4901);
  972. var aFunction = function (argument) {
  973. return isCallable(argument) ? argument : undefined;
  974. };
  975. module.exports = function (namespace, method) {
  976. return arguments.length < 2 ? aFunction(globalThis[namespace]) : globalThis[namespace] && globalThis[namespace][method];
  977. };
  978. /***/ }),
  979. /***/ 1767:
  980. /***/ ((module) => {
  981. // `GetIteratorDirect(obj)` abstract operation
  982. // https://tc39.es/proposal-iterator-helpers/#sec-getiteratordirect
  983. module.exports = function (obj) {
  984. return {
  985. iterator: obj,
  986. next: obj.next,
  987. done: false
  988. };
  989. };
  990. /***/ }),
  991. /***/ 8646:
  992. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  993. var call = __webpack_require__(9565);
  994. var anObject = __webpack_require__(8551);
  995. var getIteratorDirect = __webpack_require__(1767);
  996. var getIteratorMethod = __webpack_require__(851);
  997. module.exports = function (obj, stringHandling) {
  998. if (!stringHandling || typeof obj !== 'string') anObject(obj);
  999. var method = getIteratorMethod(obj);
  1000. return getIteratorDirect(anObject(method !== undefined ? call(method, obj) : obj));
  1001. };
  1002. /***/ }),
  1003. /***/ 851:
  1004. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1005. var classof = __webpack_require__(6955);
  1006. var getMethod = __webpack_require__(5966);
  1007. var isNullOrUndefined = __webpack_require__(4117);
  1008. var Iterators = __webpack_require__(6269);
  1009. var wellKnownSymbol = __webpack_require__(8227);
  1010. var ITERATOR = wellKnownSymbol('iterator');
  1011. module.exports = function (it) {
  1012. if (!isNullOrUndefined(it)) return getMethod(it, ITERATOR)
  1013. || getMethod(it, '@@iterator')
  1014. || Iterators[classof(it)];
  1015. };
  1016. /***/ }),
  1017. /***/ 81:
  1018. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1019. var call = __webpack_require__(9565);
  1020. var aCallable = __webpack_require__(9306);
  1021. var anObject = __webpack_require__(8551);
  1022. var tryToString = __webpack_require__(6823);
  1023. var getIteratorMethod = __webpack_require__(851);
  1024. var $TypeError = TypeError;
  1025. module.exports = function (argument, usingIterator) {
  1026. var iteratorMethod = arguments.length < 2 ? getIteratorMethod(argument) : usingIterator;
  1027. if (aCallable(iteratorMethod)) return anObject(call(iteratorMethod, argument));
  1028. throw new $TypeError(tryToString(argument) + ' is not iterable');
  1029. };
  1030. /***/ }),
  1031. /***/ 5966:
  1032. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1033. var aCallable = __webpack_require__(9306);
  1034. var isNullOrUndefined = __webpack_require__(4117);
  1035. // `GetMethod` abstract operation
  1036. // https://tc39.es/ecma262/#sec-getmethod
  1037. module.exports = function (V, P) {
  1038. var func = V[P];
  1039. return isNullOrUndefined(func) ? undefined : aCallable(func);
  1040. };
  1041. /***/ }),
  1042. /***/ 3789:
  1043. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1044. var aCallable = __webpack_require__(9306);
  1045. var anObject = __webpack_require__(8551);
  1046. var call = __webpack_require__(9565);
  1047. var toIntegerOrInfinity = __webpack_require__(1291);
  1048. var getIteratorDirect = __webpack_require__(1767);
  1049. var INVALID_SIZE = 'Invalid size';
  1050. var $RangeError = RangeError;
  1051. var $TypeError = TypeError;
  1052. var max = Math.max;
  1053. var SetRecord = function (set, intSize) {
  1054. this.set = set;
  1055. this.size = max(intSize, 0);
  1056. this.has = aCallable(set.has);
  1057. this.keys = aCallable(set.keys);
  1058. };
  1059. SetRecord.prototype = {
  1060. getIterator: function () {
  1061. return getIteratorDirect(anObject(call(this.keys, this.set)));
  1062. },
  1063. includes: function (it) {
  1064. return call(this.has, this.set, it);
  1065. }
  1066. };
  1067. // `GetSetRecord` abstract operation
  1068. // https://tc39.es/proposal-set-methods/#sec-getsetrecord
  1069. module.exports = function (obj) {
  1070. anObject(obj);
  1071. var numSize = +obj.size;
  1072. // NOTE: If size is undefined, then numSize will be NaN
  1073. // eslint-disable-next-line no-self-compare -- NaN check
  1074. if (numSize !== numSize) throw new $TypeError(INVALID_SIZE);
  1075. var intSize = toIntegerOrInfinity(numSize);
  1076. if (intSize < 0) throw new $RangeError(INVALID_SIZE);
  1077. return new SetRecord(obj, intSize);
  1078. };
  1079. /***/ }),
  1080. /***/ 4576:
  1081. /***/ (function(module) {
  1082. var check = function (it) {
  1083. return it && it.Math === Math && it;
  1084. };
  1085. // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
  1086. module.exports =
  1087. // eslint-disable-next-line es/no-global-this -- safe
  1088. check(typeof globalThis == 'object' && globalThis) ||
  1089. check(typeof window == 'object' && window) ||
  1090. // eslint-disable-next-line no-restricted-globals -- safe
  1091. check(typeof self == 'object' && self) ||
  1092. check(typeof global == 'object' && global) ||
  1093. check(typeof this == 'object' && this) ||
  1094. // eslint-disable-next-line no-new-func -- fallback
  1095. (function () { return this; })() || Function('return this')();
  1096. /***/ }),
  1097. /***/ 9297:
  1098. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1099. var uncurryThis = __webpack_require__(9504);
  1100. var toObject = __webpack_require__(8981);
  1101. var hasOwnProperty = uncurryThis({}.hasOwnProperty);
  1102. // `HasOwnProperty` abstract operation
  1103. // https://tc39.es/ecma262/#sec-hasownproperty
  1104. // eslint-disable-next-line es/no-object-hasown -- safe
  1105. module.exports = Object.hasOwn || function hasOwn(it, key) {
  1106. return hasOwnProperty(toObject(it), key);
  1107. };
  1108. /***/ }),
  1109. /***/ 421:
  1110. /***/ ((module) => {
  1111. module.exports = {};
  1112. /***/ }),
  1113. /***/ 397:
  1114. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1115. var getBuiltIn = __webpack_require__(7751);
  1116. module.exports = getBuiltIn('document', 'documentElement');
  1117. /***/ }),
  1118. /***/ 5917:
  1119. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1120. var DESCRIPTORS = __webpack_require__(3724);
  1121. var fails = __webpack_require__(9039);
  1122. var createElement = __webpack_require__(4055);
  1123. // Thanks to IE8 for its funny defineProperty
  1124. module.exports = !DESCRIPTORS && !fails(function () {
  1125. // eslint-disable-next-line es/no-object-defineproperty -- required for testing
  1126. return Object.defineProperty(createElement('div'), 'a', {
  1127. get: function () { return 7; }
  1128. }).a !== 7;
  1129. });
  1130. /***/ }),
  1131. /***/ 7055:
  1132. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1133. var uncurryThis = __webpack_require__(9504);
  1134. var fails = __webpack_require__(9039);
  1135. var classof = __webpack_require__(2195);
  1136. var $Object = Object;
  1137. var split = uncurryThis(''.split);
  1138. // fallback for non-array-like ES3 and non-enumerable old V8 strings
  1139. module.exports = fails(function () {
  1140. // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
  1141. // eslint-disable-next-line no-prototype-builtins -- safe
  1142. return !$Object('z').propertyIsEnumerable(0);
  1143. }) ? function (it) {
  1144. return classof(it) === 'String' ? split(it, '') : $Object(it);
  1145. } : $Object;
  1146. /***/ }),
  1147. /***/ 3167:
  1148. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1149. var isCallable = __webpack_require__(4901);
  1150. var isObject = __webpack_require__(34);
  1151. var setPrototypeOf = __webpack_require__(2967);
  1152. // makes subclassing work correct for wrapped built-ins
  1153. module.exports = function ($this, dummy, Wrapper) {
  1154. var NewTarget, NewTargetPrototype;
  1155. if (
  1156. // it can work only with native `setPrototypeOf`
  1157. setPrototypeOf &&
  1158. // we haven't completely correct pre-ES6 way for getting `new.target`, so use this
  1159. isCallable(NewTarget = dummy.constructor) &&
  1160. NewTarget !== Wrapper &&
  1161. isObject(NewTargetPrototype = NewTarget.prototype) &&
  1162. NewTargetPrototype !== Wrapper.prototype
  1163. ) setPrototypeOf($this, NewTargetPrototype);
  1164. return $this;
  1165. };
  1166. /***/ }),
  1167. /***/ 3706:
  1168. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1169. var uncurryThis = __webpack_require__(9504);
  1170. var isCallable = __webpack_require__(4901);
  1171. var store = __webpack_require__(7629);
  1172. var functionToString = uncurryThis(Function.toString);
  1173. // this helper broken in `core-js@3.4.1-3.4.4`, so we can't use `shared` helper
  1174. if (!isCallable(store.inspectSource)) {
  1175. store.inspectSource = function (it) {
  1176. return functionToString(it);
  1177. };
  1178. }
  1179. module.exports = store.inspectSource;
  1180. /***/ }),
  1181. /***/ 1181:
  1182. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1183. var NATIVE_WEAK_MAP = __webpack_require__(8622);
  1184. var globalThis = __webpack_require__(4576);
  1185. var isObject = __webpack_require__(34);
  1186. var createNonEnumerableProperty = __webpack_require__(6699);
  1187. var hasOwn = __webpack_require__(9297);
  1188. var shared = __webpack_require__(7629);
  1189. var sharedKey = __webpack_require__(6119);
  1190. var hiddenKeys = __webpack_require__(421);
  1191. var OBJECT_ALREADY_INITIALIZED = 'Object already initialized';
  1192. var TypeError = globalThis.TypeError;
  1193. var WeakMap = globalThis.WeakMap;
  1194. var set, get, has;
  1195. var enforce = function (it) {
  1196. return has(it) ? get(it) : set(it, {});
  1197. };
  1198. var getterFor = function (TYPE) {
  1199. return function (it) {
  1200. var state;
  1201. if (!isObject(it) || (state = get(it)).type !== TYPE) {
  1202. throw new TypeError('Incompatible receiver, ' + TYPE + ' required');
  1203. } return state;
  1204. };
  1205. };
  1206. if (NATIVE_WEAK_MAP || shared.state) {
  1207. var store = shared.state || (shared.state = new WeakMap());
  1208. /* eslint-disable no-self-assign -- prototype methods protection */
  1209. store.get = store.get;
  1210. store.has = store.has;
  1211. store.set = store.set;
  1212. /* eslint-enable no-self-assign -- prototype methods protection */
  1213. set = function (it, metadata) {
  1214. if (store.has(it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
  1215. metadata.facade = it;
  1216. store.set(it, metadata);
  1217. return metadata;
  1218. };
  1219. get = function (it) {
  1220. return store.get(it) || {};
  1221. };
  1222. has = function (it) {
  1223. return store.has(it);
  1224. };
  1225. } else {
  1226. var STATE = sharedKey('state');
  1227. hiddenKeys[STATE] = true;
  1228. set = function (it, metadata) {
  1229. if (hasOwn(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
  1230. metadata.facade = it;
  1231. createNonEnumerableProperty(it, STATE, metadata);
  1232. return metadata;
  1233. };
  1234. get = function (it) {
  1235. return hasOwn(it, STATE) ? it[STATE] : {};
  1236. };
  1237. has = function (it) {
  1238. return hasOwn(it, STATE);
  1239. };
  1240. }
  1241. module.exports = {
  1242. set: set,
  1243. get: get,
  1244. has: has,
  1245. enforce: enforce,
  1246. getterFor: getterFor
  1247. };
  1248. /***/ }),
  1249. /***/ 4209:
  1250. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1251. var wellKnownSymbol = __webpack_require__(8227);
  1252. var Iterators = __webpack_require__(6269);
  1253. var ITERATOR = wellKnownSymbol('iterator');
  1254. var ArrayPrototype = Array.prototype;
  1255. // check on default Array iterator
  1256. module.exports = function (it) {
  1257. return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it);
  1258. };
  1259. /***/ }),
  1260. /***/ 4376:
  1261. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1262. var classof = __webpack_require__(2195);
  1263. // `IsArray` abstract operation
  1264. // https://tc39.es/ecma262/#sec-isarray
  1265. // eslint-disable-next-line es/no-array-isarray -- safe
  1266. module.exports = Array.isArray || function isArray(argument) {
  1267. return classof(argument) === 'Array';
  1268. };
  1269. /***/ }),
  1270. /***/ 1108:
  1271. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1272. var classof = __webpack_require__(6955);
  1273. module.exports = function (it) {
  1274. var klass = classof(it);
  1275. return klass === 'BigInt64Array' || klass === 'BigUint64Array';
  1276. };
  1277. /***/ }),
  1278. /***/ 4901:
  1279. /***/ ((module) => {
  1280. // https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot
  1281. var documentAll = typeof document == 'object' && document.all;
  1282. // `IsCallable` abstract operation
  1283. // https://tc39.es/ecma262/#sec-iscallable
  1284. // eslint-disable-next-line unicorn/no-typeof-undefined -- required for testing
  1285. module.exports = typeof documentAll == 'undefined' && documentAll !== undefined ? function (argument) {
  1286. return typeof argument == 'function' || argument === documentAll;
  1287. } : function (argument) {
  1288. return typeof argument == 'function';
  1289. };
  1290. /***/ }),
  1291. /***/ 2796:
  1292. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1293. var fails = __webpack_require__(9039);
  1294. var isCallable = __webpack_require__(4901);
  1295. var replacement = /#|\.prototype\./;
  1296. var isForced = function (feature, detection) {
  1297. var value = data[normalize(feature)];
  1298. return value === POLYFILL ? true
  1299. : value === NATIVE ? false
  1300. : isCallable(detection) ? fails(detection)
  1301. : !!detection;
  1302. };
  1303. var normalize = isForced.normalize = function (string) {
  1304. return String(string).replace(replacement, '.').toLowerCase();
  1305. };
  1306. var data = isForced.data = {};
  1307. var NATIVE = isForced.NATIVE = 'N';
  1308. var POLYFILL = isForced.POLYFILL = 'P';
  1309. module.exports = isForced;
  1310. /***/ }),
  1311. /***/ 4117:
  1312. /***/ ((module) => {
  1313. // we can't use just `it == null` since of `document.all` special case
  1314. // https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec
  1315. module.exports = function (it) {
  1316. return it === null || it === undefined;
  1317. };
  1318. /***/ }),
  1319. /***/ 34:
  1320. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1321. var isCallable = __webpack_require__(4901);
  1322. module.exports = function (it) {
  1323. return typeof it == 'object' ? it !== null : isCallable(it);
  1324. };
  1325. /***/ }),
  1326. /***/ 3925:
  1327. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1328. var isObject = __webpack_require__(34);
  1329. module.exports = function (argument) {
  1330. return isObject(argument) || argument === null;
  1331. };
  1332. /***/ }),
  1333. /***/ 6395:
  1334. /***/ ((module) => {
  1335. module.exports = false;
  1336. /***/ }),
  1337. /***/ 757:
  1338. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1339. var getBuiltIn = __webpack_require__(7751);
  1340. var isCallable = __webpack_require__(4901);
  1341. var isPrototypeOf = __webpack_require__(1625);
  1342. var USE_SYMBOL_AS_UID = __webpack_require__(7040);
  1343. var $Object = Object;
  1344. module.exports = USE_SYMBOL_AS_UID ? function (it) {
  1345. return typeof it == 'symbol';
  1346. } : function (it) {
  1347. var $Symbol = getBuiltIn('Symbol');
  1348. return isCallable($Symbol) && isPrototypeOf($Symbol.prototype, $Object(it));
  1349. };
  1350. /***/ }),
  1351. /***/ 507:
  1352. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1353. var call = __webpack_require__(9565);
  1354. module.exports = function (record, fn, ITERATOR_INSTEAD_OF_RECORD) {
  1355. var iterator = ITERATOR_INSTEAD_OF_RECORD ? record : record.iterator;
  1356. var next = record.next;
  1357. var step, result;
  1358. while (!(step = call(next, iterator)).done) {
  1359. result = fn(step.value);
  1360. if (result !== undefined) return result;
  1361. }
  1362. };
  1363. /***/ }),
  1364. /***/ 2652:
  1365. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1366. var bind = __webpack_require__(6080);
  1367. var call = __webpack_require__(9565);
  1368. var anObject = __webpack_require__(8551);
  1369. var tryToString = __webpack_require__(6823);
  1370. var isArrayIteratorMethod = __webpack_require__(4209);
  1371. var lengthOfArrayLike = __webpack_require__(6198);
  1372. var isPrototypeOf = __webpack_require__(1625);
  1373. var getIterator = __webpack_require__(81);
  1374. var getIteratorMethod = __webpack_require__(851);
  1375. var iteratorClose = __webpack_require__(9539);
  1376. var $TypeError = TypeError;
  1377. var Result = function (stopped, result) {
  1378. this.stopped = stopped;
  1379. this.result = result;
  1380. };
  1381. var ResultPrototype = Result.prototype;
  1382. module.exports = function (iterable, unboundFunction, options) {
  1383. var that = options && options.that;
  1384. var AS_ENTRIES = !!(options && options.AS_ENTRIES);
  1385. var IS_RECORD = !!(options && options.IS_RECORD);
  1386. var IS_ITERATOR = !!(options && options.IS_ITERATOR);
  1387. var INTERRUPTED = !!(options && options.INTERRUPTED);
  1388. var fn = bind(unboundFunction, that);
  1389. var iterator, iterFn, index, length, result, next, step;
  1390. var stop = function (condition) {
  1391. if (iterator) iteratorClose(iterator, 'normal', condition);
  1392. return new Result(true, condition);
  1393. };
  1394. var callFn = function (value) {
  1395. if (AS_ENTRIES) {
  1396. anObject(value);
  1397. return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]);
  1398. } return INTERRUPTED ? fn(value, stop) : fn(value);
  1399. };
  1400. if (IS_RECORD) {
  1401. iterator = iterable.iterator;
  1402. } else if (IS_ITERATOR) {
  1403. iterator = iterable;
  1404. } else {
  1405. iterFn = getIteratorMethod(iterable);
  1406. if (!iterFn) throw new $TypeError(tryToString(iterable) + ' is not iterable');
  1407. // optimisation for array iterators
  1408. if (isArrayIteratorMethod(iterFn)) {
  1409. for (index = 0, length = lengthOfArrayLike(iterable); length > index; index++) {
  1410. result = callFn(iterable[index]);
  1411. if (result && isPrototypeOf(ResultPrototype, result)) return result;
  1412. } return new Result(false);
  1413. }
  1414. iterator = getIterator(iterable, iterFn);
  1415. }
  1416. next = IS_RECORD ? iterable.next : iterator.next;
  1417. while (!(step = call(next, iterator)).done) {
  1418. try {
  1419. result = callFn(step.value);
  1420. } catch (error) {
  1421. iteratorClose(iterator, 'throw', error);
  1422. }
  1423. if (typeof result == 'object' && result && isPrototypeOf(ResultPrototype, result)) return result;
  1424. } return new Result(false);
  1425. };
  1426. /***/ }),
  1427. /***/ 9539:
  1428. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1429. var call = __webpack_require__(9565);
  1430. var anObject = __webpack_require__(8551);
  1431. var getMethod = __webpack_require__(5966);
  1432. module.exports = function (iterator, kind, value) {
  1433. var innerResult, innerError;
  1434. anObject(iterator);
  1435. try {
  1436. innerResult = getMethod(iterator, 'return');
  1437. if (!innerResult) {
  1438. if (kind === 'throw') throw value;
  1439. return value;
  1440. }
  1441. innerResult = call(innerResult, iterator);
  1442. } catch (error) {
  1443. innerError = true;
  1444. innerResult = error;
  1445. }
  1446. if (kind === 'throw') throw value;
  1447. if (innerError) throw innerResult;
  1448. anObject(innerResult);
  1449. return value;
  1450. };
  1451. /***/ }),
  1452. /***/ 9462:
  1453. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1454. var call = __webpack_require__(9565);
  1455. var create = __webpack_require__(2360);
  1456. var createNonEnumerableProperty = __webpack_require__(6699);
  1457. var defineBuiltIns = __webpack_require__(6279);
  1458. var wellKnownSymbol = __webpack_require__(8227);
  1459. var InternalStateModule = __webpack_require__(1181);
  1460. var getMethod = __webpack_require__(5966);
  1461. var IteratorPrototype = (__webpack_require__(7657).IteratorPrototype);
  1462. var createIterResultObject = __webpack_require__(2529);
  1463. var iteratorClose = __webpack_require__(9539);
  1464. var TO_STRING_TAG = wellKnownSymbol('toStringTag');
  1465. var ITERATOR_HELPER = 'IteratorHelper';
  1466. var WRAP_FOR_VALID_ITERATOR = 'WrapForValidIterator';
  1467. var setInternalState = InternalStateModule.set;
  1468. var createIteratorProxyPrototype = function (IS_ITERATOR) {
  1469. var getInternalState = InternalStateModule.getterFor(IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER);
  1470. return defineBuiltIns(create(IteratorPrototype), {
  1471. next: function next() {
  1472. var state = getInternalState(this);
  1473. // for simplification:
  1474. // for `%WrapForValidIteratorPrototype%.next` our `nextHandler` returns `IterResultObject`
  1475. // for `%IteratorHelperPrototype%.next` - just a value
  1476. if (IS_ITERATOR) return state.nextHandler();
  1477. try {
  1478. var result = state.done ? undefined : state.nextHandler();
  1479. return createIterResultObject(result, state.done);
  1480. } catch (error) {
  1481. state.done = true;
  1482. throw error;
  1483. }
  1484. },
  1485. 'return': function () {
  1486. var state = getInternalState(this);
  1487. var iterator = state.iterator;
  1488. state.done = true;
  1489. if (IS_ITERATOR) {
  1490. var returnMethod = getMethod(iterator, 'return');
  1491. return returnMethod ? call(returnMethod, iterator) : createIterResultObject(undefined, true);
  1492. }
  1493. if (state.inner) try {
  1494. iteratorClose(state.inner.iterator, 'normal');
  1495. } catch (error) {
  1496. return iteratorClose(iterator, 'throw', error);
  1497. }
  1498. iteratorClose(iterator, 'normal');
  1499. return createIterResultObject(undefined, true);
  1500. }
  1501. });
  1502. };
  1503. var WrapForValidIteratorPrototype = createIteratorProxyPrototype(true);
  1504. var IteratorHelperPrototype = createIteratorProxyPrototype(false);
  1505. createNonEnumerableProperty(IteratorHelperPrototype, TO_STRING_TAG, 'Iterator Helper');
  1506. module.exports = function (nextHandler, IS_ITERATOR) {
  1507. var IteratorProxy = function Iterator(record, state) {
  1508. if (state) {
  1509. state.iterator = record.iterator;
  1510. state.next = record.next;
  1511. } else state = record;
  1512. state.type = IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER;
  1513. state.nextHandler = nextHandler;
  1514. state.counter = 0;
  1515. state.done = false;
  1516. setInternalState(this, state);
  1517. };
  1518. IteratorProxy.prototype = IS_ITERATOR ? WrapForValidIteratorPrototype : IteratorHelperPrototype;
  1519. return IteratorProxy;
  1520. };
  1521. /***/ }),
  1522. /***/ 713:
  1523. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1524. var call = __webpack_require__(9565);
  1525. var aCallable = __webpack_require__(9306);
  1526. var anObject = __webpack_require__(8551);
  1527. var getIteratorDirect = __webpack_require__(1767);
  1528. var createIteratorProxy = __webpack_require__(9462);
  1529. var callWithSafeIterationClosing = __webpack_require__(6319);
  1530. var IteratorProxy = createIteratorProxy(function () {
  1531. var iterator = this.iterator;
  1532. var result = anObject(call(this.next, iterator));
  1533. var done = this.done = !!result.done;
  1534. if (!done) return callWithSafeIterationClosing(iterator, this.mapper, [result.value, this.counter++], true);
  1535. });
  1536. // `Iterator.prototype.map` method
  1537. // https://github.com/tc39/proposal-iterator-helpers
  1538. module.exports = function map(mapper) {
  1539. anObject(this);
  1540. aCallable(mapper);
  1541. return new IteratorProxy(getIteratorDirect(this), {
  1542. mapper: mapper
  1543. });
  1544. };
  1545. /***/ }),
  1546. /***/ 7657:
  1547. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1548. var fails = __webpack_require__(9039);
  1549. var isCallable = __webpack_require__(4901);
  1550. var isObject = __webpack_require__(34);
  1551. var create = __webpack_require__(2360);
  1552. var getPrototypeOf = __webpack_require__(2787);
  1553. var defineBuiltIn = __webpack_require__(6840);
  1554. var wellKnownSymbol = __webpack_require__(8227);
  1555. var IS_PURE = __webpack_require__(6395);
  1556. var ITERATOR = wellKnownSymbol('iterator');
  1557. var BUGGY_SAFARI_ITERATORS = false;
  1558. // `%IteratorPrototype%` object
  1559. // https://tc39.es/ecma262/#sec-%iteratorprototype%-object
  1560. var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;
  1561. /* eslint-disable es/no-array-prototype-keys -- safe */
  1562. if ([].keys) {
  1563. arrayIterator = [].keys();
  1564. // Safari 8 has buggy iterators w/o `next`
  1565. if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;
  1566. else {
  1567. PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator));
  1568. if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;
  1569. }
  1570. }
  1571. var NEW_ITERATOR_PROTOTYPE = !isObject(IteratorPrototype) || fails(function () {
  1572. var test = {};
  1573. // FF44- legacy iterators case
  1574. return IteratorPrototype[ITERATOR].call(test) !== test;
  1575. });
  1576. if (NEW_ITERATOR_PROTOTYPE) IteratorPrototype = {};
  1577. else if (IS_PURE) IteratorPrototype = create(IteratorPrototype);
  1578. // `%IteratorPrototype%[@@iterator]()` method
  1579. // https://tc39.es/ecma262/#sec-%iteratorprototype%-@@iterator
  1580. if (!isCallable(IteratorPrototype[ITERATOR])) {
  1581. defineBuiltIn(IteratorPrototype, ITERATOR, function () {
  1582. return this;
  1583. });
  1584. }
  1585. module.exports = {
  1586. IteratorPrototype: IteratorPrototype,
  1587. BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS
  1588. };
  1589. /***/ }),
  1590. /***/ 6269:
  1591. /***/ ((module) => {
  1592. module.exports = {};
  1593. /***/ }),
  1594. /***/ 6198:
  1595. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1596. var toLength = __webpack_require__(8014);
  1597. // `LengthOfArrayLike` abstract operation
  1598. // https://tc39.es/ecma262/#sec-lengthofarraylike
  1599. module.exports = function (obj) {
  1600. return toLength(obj.length);
  1601. };
  1602. /***/ }),
  1603. /***/ 283:
  1604. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1605. var uncurryThis = __webpack_require__(9504);
  1606. var fails = __webpack_require__(9039);
  1607. var isCallable = __webpack_require__(4901);
  1608. var hasOwn = __webpack_require__(9297);
  1609. var DESCRIPTORS = __webpack_require__(3724);
  1610. var CONFIGURABLE_FUNCTION_NAME = (__webpack_require__(350).CONFIGURABLE);
  1611. var inspectSource = __webpack_require__(3706);
  1612. var InternalStateModule = __webpack_require__(1181);
  1613. var enforceInternalState = InternalStateModule.enforce;
  1614. var getInternalState = InternalStateModule.get;
  1615. var $String = String;
  1616. // eslint-disable-next-line es/no-object-defineproperty -- safe
  1617. var defineProperty = Object.defineProperty;
  1618. var stringSlice = uncurryThis(''.slice);
  1619. var replace = uncurryThis(''.replace);
  1620. var join = uncurryThis([].join);
  1621. var CONFIGURABLE_LENGTH = DESCRIPTORS && !fails(function () {
  1622. return defineProperty(function () { /* empty */ }, 'length', { value: 8 }).length !== 8;
  1623. });
  1624. var TEMPLATE = String(String).split('String');
  1625. var makeBuiltIn = module.exports = function (value, name, options) {
  1626. if (stringSlice($String(name), 0, 7) === 'Symbol(') {
  1627. name = '[' + replace($String(name), /^Symbol\(([^)]*)\).*$/, '$1') + ']';
  1628. }
  1629. if (options && options.getter) name = 'get ' + name;
  1630. if (options && options.setter) name = 'set ' + name;
  1631. if (!hasOwn(value, 'name') || (CONFIGURABLE_FUNCTION_NAME && value.name !== name)) {
  1632. if (DESCRIPTORS) defineProperty(value, 'name', { value: name, configurable: true });
  1633. else value.name = name;
  1634. }
  1635. if (CONFIGURABLE_LENGTH && options && hasOwn(options, 'arity') && value.length !== options.arity) {
  1636. defineProperty(value, 'length', { value: options.arity });
  1637. }
  1638. try {
  1639. if (options && hasOwn(options, 'constructor') && options.constructor) {
  1640. if (DESCRIPTORS) defineProperty(value, 'prototype', { writable: false });
  1641. // in V8 ~ Chrome 53, prototypes of some methods, like `Array.prototype.values`, are non-writable
  1642. } else if (value.prototype) value.prototype = undefined;
  1643. } catch (error) { /* empty */ }
  1644. var state = enforceInternalState(value);
  1645. if (!hasOwn(state, 'source')) {
  1646. state.source = join(TEMPLATE, typeof name == 'string' ? name : '');
  1647. } return value;
  1648. };
  1649. // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
  1650. // eslint-disable-next-line no-extend-native -- required
  1651. Function.prototype.toString = makeBuiltIn(function toString() {
  1652. return isCallable(this) && getInternalState(this).source || inspectSource(this);
  1653. }, 'toString');
  1654. /***/ }),
  1655. /***/ 741:
  1656. /***/ ((module) => {
  1657. var ceil = Math.ceil;
  1658. var floor = Math.floor;
  1659. // `Math.trunc` method
  1660. // https://tc39.es/ecma262/#sec-math.trunc
  1661. // eslint-disable-next-line es/no-math-trunc -- safe
  1662. module.exports = Math.trunc || function trunc(x) {
  1663. var n = +x;
  1664. return (n > 0 ? floor : ceil)(n);
  1665. };
  1666. /***/ }),
  1667. /***/ 6043:
  1668. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1669. var aCallable = __webpack_require__(9306);
  1670. var $TypeError = TypeError;
  1671. var PromiseCapability = function (C) {
  1672. var resolve, reject;
  1673. this.promise = new C(function ($$resolve, $$reject) {
  1674. if (resolve !== undefined || reject !== undefined) throw new $TypeError('Bad Promise constructor');
  1675. resolve = $$resolve;
  1676. reject = $$reject;
  1677. });
  1678. this.resolve = aCallable(resolve);
  1679. this.reject = aCallable(reject);
  1680. };
  1681. // `NewPromiseCapability` abstract operation
  1682. // https://tc39.es/ecma262/#sec-newpromisecapability
  1683. module.exports.f = function (C) {
  1684. return new PromiseCapability(C);
  1685. };
  1686. /***/ }),
  1687. /***/ 2603:
  1688. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1689. var toString = __webpack_require__(655);
  1690. module.exports = function (argument, $default) {
  1691. return argument === undefined ? arguments.length < 2 ? '' : $default : toString(argument);
  1692. };
  1693. /***/ }),
  1694. /***/ 4149:
  1695. /***/ ((module) => {
  1696. var $RangeError = RangeError;
  1697. module.exports = function (it) {
  1698. // eslint-disable-next-line no-self-compare -- NaN check
  1699. if (it === it) return it;
  1700. throw new $RangeError('NaN is not allowed');
  1701. };
  1702. /***/ }),
  1703. /***/ 2360:
  1704. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1705. /* global ActiveXObject -- old IE, WSH */
  1706. var anObject = __webpack_require__(8551);
  1707. var definePropertiesModule = __webpack_require__(6801);
  1708. var enumBugKeys = __webpack_require__(8727);
  1709. var hiddenKeys = __webpack_require__(421);
  1710. var html = __webpack_require__(397);
  1711. var documentCreateElement = __webpack_require__(4055);
  1712. var sharedKey = __webpack_require__(6119);
  1713. var GT = '>';
  1714. var LT = '<';
  1715. var PROTOTYPE = 'prototype';
  1716. var SCRIPT = 'script';
  1717. var IE_PROTO = sharedKey('IE_PROTO');
  1718. var EmptyConstructor = function () { /* empty */ };
  1719. var scriptTag = function (content) {
  1720. return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;
  1721. };
  1722. // Create object with fake `null` prototype: use ActiveX Object with cleared prototype
  1723. var NullProtoObjectViaActiveX = function (activeXDocument) {
  1724. activeXDocument.write(scriptTag(''));
  1725. activeXDocument.close();
  1726. var temp = activeXDocument.parentWindow.Object;
  1727. // eslint-disable-next-line no-useless-assignment -- avoid memory leak
  1728. activeXDocument = null;
  1729. return temp;
  1730. };
  1731. // Create object with fake `null` prototype: use iframe Object with cleared prototype
  1732. var NullProtoObjectViaIFrame = function () {
  1733. // Thrash, waste and sodomy: IE GC bug
  1734. var iframe = documentCreateElement('iframe');
  1735. var JS = 'java' + SCRIPT + ':';
  1736. var iframeDocument;
  1737. iframe.style.display = 'none';
  1738. html.appendChild(iframe);
  1739. // https://github.com/zloirock/core-js/issues/475
  1740. iframe.src = String(JS);
  1741. iframeDocument = iframe.contentWindow.document;
  1742. iframeDocument.open();
  1743. iframeDocument.write(scriptTag('document.F=Object'));
  1744. iframeDocument.close();
  1745. return iframeDocument.F;
  1746. };
  1747. // Check for document.domain and active x support
  1748. // No need to use active x approach when document.domain is not set
  1749. // see https://github.com/es-shims/es5-shim/issues/150
  1750. // variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
  1751. // avoid IE GC bug
  1752. var activeXDocument;
  1753. var NullProtoObject = function () {
  1754. try {
  1755. activeXDocument = new ActiveXObject('htmlfile');
  1756. } catch (error) { /* ignore */ }
  1757. NullProtoObject = typeof document != 'undefined'
  1758. ? document.domain && activeXDocument
  1759. ? NullProtoObjectViaActiveX(activeXDocument) // old IE
  1760. : NullProtoObjectViaIFrame()
  1761. : NullProtoObjectViaActiveX(activeXDocument); // WSH
  1762. var length = enumBugKeys.length;
  1763. while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];
  1764. return NullProtoObject();
  1765. };
  1766. hiddenKeys[IE_PROTO] = true;
  1767. // `Object.create` method
  1768. // https://tc39.es/ecma262/#sec-object.create
  1769. // eslint-disable-next-line es/no-object-create -- safe
  1770. module.exports = Object.create || function create(O, Properties) {
  1771. var result;
  1772. if (O !== null) {
  1773. EmptyConstructor[PROTOTYPE] = anObject(O);
  1774. result = new EmptyConstructor();
  1775. EmptyConstructor[PROTOTYPE] = null;
  1776. // add "__proto__" for Object.getPrototypeOf polyfill
  1777. result[IE_PROTO] = O;
  1778. } else result = NullProtoObject();
  1779. return Properties === undefined ? result : definePropertiesModule.f(result, Properties);
  1780. };
  1781. /***/ }),
  1782. /***/ 6801:
  1783. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  1784. var DESCRIPTORS = __webpack_require__(3724);
  1785. var V8_PROTOTYPE_DEFINE_BUG = __webpack_require__(8686);
  1786. var definePropertyModule = __webpack_require__(4913);
  1787. var anObject = __webpack_require__(8551);
  1788. var toIndexedObject = __webpack_require__(5397);
  1789. var objectKeys = __webpack_require__(1072);
  1790. // `Object.defineProperties` method
  1791. // https://tc39.es/ecma262/#sec-object.defineproperties
  1792. // eslint-disable-next-line es/no-object-defineproperties -- safe
  1793. exports.f = DESCRIPTORS && !V8_PROTOTYPE_DEFINE_BUG ? Object.defineProperties : function defineProperties(O, Properties) {
  1794. anObject(O);
  1795. var props = toIndexedObject(Properties);
  1796. var keys = objectKeys(Properties);
  1797. var length = keys.length;
  1798. var index = 0;
  1799. var key;
  1800. while (length > index) definePropertyModule.f(O, key = keys[index++], props[key]);
  1801. return O;
  1802. };
  1803. /***/ }),
  1804. /***/ 4913:
  1805. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  1806. var DESCRIPTORS = __webpack_require__(3724);
  1807. var IE8_DOM_DEFINE = __webpack_require__(5917);
  1808. var V8_PROTOTYPE_DEFINE_BUG = __webpack_require__(8686);
  1809. var anObject = __webpack_require__(8551);
  1810. var toPropertyKey = __webpack_require__(6969);
  1811. var $TypeError = TypeError;
  1812. // eslint-disable-next-line es/no-object-defineproperty -- safe
  1813. var $defineProperty = Object.defineProperty;
  1814. // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
  1815. var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  1816. var ENUMERABLE = 'enumerable';
  1817. var CONFIGURABLE = 'configurable';
  1818. var WRITABLE = 'writable';
  1819. // `Object.defineProperty` method
  1820. // https://tc39.es/ecma262/#sec-object.defineproperty
  1821. exports.f = DESCRIPTORS ? V8_PROTOTYPE_DEFINE_BUG ? function defineProperty(O, P, Attributes) {
  1822. anObject(O);
  1823. P = toPropertyKey(P);
  1824. anObject(Attributes);
  1825. if (typeof O === 'function' && P === 'prototype' && 'value' in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) {
  1826. var current = $getOwnPropertyDescriptor(O, P);
  1827. if (current && current[WRITABLE]) {
  1828. O[P] = Attributes.value;
  1829. Attributes = {
  1830. configurable: CONFIGURABLE in Attributes ? Attributes[CONFIGURABLE] : current[CONFIGURABLE],
  1831. enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE],
  1832. writable: false
  1833. };
  1834. }
  1835. } return $defineProperty(O, P, Attributes);
  1836. } : $defineProperty : function defineProperty(O, P, Attributes) {
  1837. anObject(O);
  1838. P = toPropertyKey(P);
  1839. anObject(Attributes);
  1840. if (IE8_DOM_DEFINE) try {
  1841. return $defineProperty(O, P, Attributes);
  1842. } catch (error) { /* empty */ }
  1843. if ('get' in Attributes || 'set' in Attributes) throw new $TypeError('Accessors not supported');
  1844. if ('value' in Attributes) O[P] = Attributes.value;
  1845. return O;
  1846. };
  1847. /***/ }),
  1848. /***/ 7347:
  1849. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  1850. var DESCRIPTORS = __webpack_require__(3724);
  1851. var call = __webpack_require__(9565);
  1852. var propertyIsEnumerableModule = __webpack_require__(8773);
  1853. var createPropertyDescriptor = __webpack_require__(6980);
  1854. var toIndexedObject = __webpack_require__(5397);
  1855. var toPropertyKey = __webpack_require__(6969);
  1856. var hasOwn = __webpack_require__(9297);
  1857. var IE8_DOM_DEFINE = __webpack_require__(5917);
  1858. // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
  1859. var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  1860. // `Object.getOwnPropertyDescriptor` method
  1861. // https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
  1862. exports.f = DESCRIPTORS ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
  1863. O = toIndexedObject(O);
  1864. P = toPropertyKey(P);
  1865. if (IE8_DOM_DEFINE) try {
  1866. return $getOwnPropertyDescriptor(O, P);
  1867. } catch (error) { /* empty */ }
  1868. if (hasOwn(O, P)) return createPropertyDescriptor(!call(propertyIsEnumerableModule.f, O, P), O[P]);
  1869. };
  1870. /***/ }),
  1871. /***/ 8480:
  1872. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  1873. var internalObjectKeys = __webpack_require__(1828);
  1874. var enumBugKeys = __webpack_require__(8727);
  1875. var hiddenKeys = enumBugKeys.concat('length', 'prototype');
  1876. // `Object.getOwnPropertyNames` method
  1877. // https://tc39.es/ecma262/#sec-object.getownpropertynames
  1878. // eslint-disable-next-line es/no-object-getownpropertynames -- safe
  1879. exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
  1880. return internalObjectKeys(O, hiddenKeys);
  1881. };
  1882. /***/ }),
  1883. /***/ 3717:
  1884. /***/ ((__unused_webpack_module, exports) => {
  1885. // eslint-disable-next-line es/no-object-getownpropertysymbols -- safe
  1886. exports.f = Object.getOwnPropertySymbols;
  1887. /***/ }),
  1888. /***/ 2787:
  1889. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1890. var hasOwn = __webpack_require__(9297);
  1891. var isCallable = __webpack_require__(4901);
  1892. var toObject = __webpack_require__(8981);
  1893. var sharedKey = __webpack_require__(6119);
  1894. var CORRECT_PROTOTYPE_GETTER = __webpack_require__(2211);
  1895. var IE_PROTO = sharedKey('IE_PROTO');
  1896. var $Object = Object;
  1897. var ObjectPrototype = $Object.prototype;
  1898. // `Object.getPrototypeOf` method
  1899. // https://tc39.es/ecma262/#sec-object.getprototypeof
  1900. // eslint-disable-next-line es/no-object-getprototypeof -- safe
  1901. module.exports = CORRECT_PROTOTYPE_GETTER ? $Object.getPrototypeOf : function (O) {
  1902. var object = toObject(O);
  1903. if (hasOwn(object, IE_PROTO)) return object[IE_PROTO];
  1904. var constructor = object.constructor;
  1905. if (isCallable(constructor) && object instanceof constructor) {
  1906. return constructor.prototype;
  1907. } return object instanceof $Object ? ObjectPrototype : null;
  1908. };
  1909. /***/ }),
  1910. /***/ 1625:
  1911. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1912. var uncurryThis = __webpack_require__(9504);
  1913. module.exports = uncurryThis({}.isPrototypeOf);
  1914. /***/ }),
  1915. /***/ 1828:
  1916. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1917. var uncurryThis = __webpack_require__(9504);
  1918. var hasOwn = __webpack_require__(9297);
  1919. var toIndexedObject = __webpack_require__(5397);
  1920. var indexOf = (__webpack_require__(9617).indexOf);
  1921. var hiddenKeys = __webpack_require__(421);
  1922. var push = uncurryThis([].push);
  1923. module.exports = function (object, names) {
  1924. var O = toIndexedObject(object);
  1925. var i = 0;
  1926. var result = [];
  1927. var key;
  1928. for (key in O) !hasOwn(hiddenKeys, key) && hasOwn(O, key) && push(result, key);
  1929. // Don't enum bug & hidden keys
  1930. while (names.length > i) if (hasOwn(O, key = names[i++])) {
  1931. ~indexOf(result, key) || push(result, key);
  1932. }
  1933. return result;
  1934. };
  1935. /***/ }),
  1936. /***/ 1072:
  1937. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1938. var internalObjectKeys = __webpack_require__(1828);
  1939. var enumBugKeys = __webpack_require__(8727);
  1940. // `Object.keys` method
  1941. // https://tc39.es/ecma262/#sec-object.keys
  1942. // eslint-disable-next-line es/no-object-keys -- safe
  1943. module.exports = Object.keys || function keys(O) {
  1944. return internalObjectKeys(O, enumBugKeys);
  1945. };
  1946. /***/ }),
  1947. /***/ 8773:
  1948. /***/ ((__unused_webpack_module, exports) => {
  1949. var $propertyIsEnumerable = {}.propertyIsEnumerable;
  1950. // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
  1951. var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  1952. // Nashorn ~ JDK8 bug
  1953. var NASHORN_BUG = getOwnPropertyDescriptor && !$propertyIsEnumerable.call({ 1: 2 }, 1);
  1954. // `Object.prototype.propertyIsEnumerable` method implementation
  1955. // https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
  1956. exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
  1957. var descriptor = getOwnPropertyDescriptor(this, V);
  1958. return !!descriptor && descriptor.enumerable;
  1959. } : $propertyIsEnumerable;
  1960. /***/ }),
  1961. /***/ 2967:
  1962. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1963. /* eslint-disable no-proto -- safe */
  1964. var uncurryThisAccessor = __webpack_require__(6706);
  1965. var isObject = __webpack_require__(34);
  1966. var requireObjectCoercible = __webpack_require__(7750);
  1967. var aPossiblePrototype = __webpack_require__(3506);
  1968. // `Object.setPrototypeOf` method
  1969. // https://tc39.es/ecma262/#sec-object.setprototypeof
  1970. // Works with __proto__ only. Old v8 can't work with null proto objects.
  1971. // eslint-disable-next-line es/no-object-setprototypeof -- safe
  1972. module.exports = Object.setPrototypeOf || ('__proto__' in {} ? function () {
  1973. var CORRECT_SETTER = false;
  1974. var test = {};
  1975. var setter;
  1976. try {
  1977. setter = uncurryThisAccessor(Object.prototype, '__proto__', 'set');
  1978. setter(test, []);
  1979. CORRECT_SETTER = test instanceof Array;
  1980. } catch (error) { /* empty */ }
  1981. return function setPrototypeOf(O, proto) {
  1982. requireObjectCoercible(O);
  1983. aPossiblePrototype(proto);
  1984. if (!isObject(O)) return O;
  1985. if (CORRECT_SETTER) setter(O, proto);
  1986. else O.__proto__ = proto;
  1987. return O;
  1988. };
  1989. }() : undefined);
  1990. /***/ }),
  1991. /***/ 4270:
  1992. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1993. var call = __webpack_require__(9565);
  1994. var isCallable = __webpack_require__(4901);
  1995. var isObject = __webpack_require__(34);
  1996. var $TypeError = TypeError;
  1997. // `OrdinaryToPrimitive` abstract operation
  1998. // https://tc39.es/ecma262/#sec-ordinarytoprimitive
  1999. module.exports = function (input, pref) {
  2000. var fn, val;
  2001. if (pref === 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
  2002. if (isCallable(fn = input.valueOf) && !isObject(val = call(fn, input))) return val;
  2003. if (pref !== 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
  2004. throw new $TypeError("Can't convert object to primitive value");
  2005. };
  2006. /***/ }),
  2007. /***/ 5031:
  2008. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2009. var getBuiltIn = __webpack_require__(7751);
  2010. var uncurryThis = __webpack_require__(9504);
  2011. var getOwnPropertyNamesModule = __webpack_require__(8480);
  2012. var getOwnPropertySymbolsModule = __webpack_require__(3717);
  2013. var anObject = __webpack_require__(8551);
  2014. var concat = uncurryThis([].concat);
  2015. // all object keys, includes non-enumerable and symbols
  2016. module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
  2017. var keys = getOwnPropertyNamesModule.f(anObject(it));
  2018. var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
  2019. return getOwnPropertySymbols ? concat(keys, getOwnPropertySymbols(it)) : keys;
  2020. };
  2021. /***/ }),
  2022. /***/ 8235:
  2023. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2024. var uncurryThis = __webpack_require__(9504);
  2025. var hasOwn = __webpack_require__(9297);
  2026. var $SyntaxError = SyntaxError;
  2027. var $parseInt = parseInt;
  2028. var fromCharCode = String.fromCharCode;
  2029. var at = uncurryThis(''.charAt);
  2030. var slice = uncurryThis(''.slice);
  2031. var exec = uncurryThis(/./.exec);
  2032. var codePoints = {
  2033. '\\"': '"',
  2034. '\\\\': '\\',
  2035. '\\/': '/',
  2036. '\\b': '\b',
  2037. '\\f': '\f',
  2038. '\\n': '\n',
  2039. '\\r': '\r',
  2040. '\\t': '\t'
  2041. };
  2042. var IS_4_HEX_DIGITS = /^[\da-f]{4}$/i;
  2043. // eslint-disable-next-line regexp/no-control-character -- safe
  2044. var IS_C0_CONTROL_CODE = /^[\u0000-\u001F]$/;
  2045. module.exports = function (source, i) {
  2046. var unterminated = true;
  2047. var value = '';
  2048. while (i < source.length) {
  2049. var chr = at(source, i);
  2050. if (chr === '\\') {
  2051. var twoChars = slice(source, i, i + 2);
  2052. if (hasOwn(codePoints, twoChars)) {
  2053. value += codePoints[twoChars];
  2054. i += 2;
  2055. } else if (twoChars === '\\u') {
  2056. i += 2;
  2057. var fourHexDigits = slice(source, i, i + 4);
  2058. if (!exec(IS_4_HEX_DIGITS, fourHexDigits)) throw new $SyntaxError('Bad Unicode escape at: ' + i);
  2059. value += fromCharCode($parseInt(fourHexDigits, 16));
  2060. i += 4;
  2061. } else throw new $SyntaxError('Unknown escape sequence: "' + twoChars + '"');
  2062. } else if (chr === '"') {
  2063. unterminated = false;
  2064. i++;
  2065. break;
  2066. } else {
  2067. if (exec(IS_C0_CONTROL_CODE, chr)) throw new $SyntaxError('Bad control character in string literal at: ' + i);
  2068. value += chr;
  2069. i++;
  2070. }
  2071. }
  2072. if (unterminated) throw new $SyntaxError('Unterminated string at: ' + i);
  2073. return { value: value, end: i };
  2074. };
  2075. /***/ }),
  2076. /***/ 7750:
  2077. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2078. var isNullOrUndefined = __webpack_require__(4117);
  2079. var $TypeError = TypeError;
  2080. // `RequireObjectCoercible` abstract operation
  2081. // https://tc39.es/ecma262/#sec-requireobjectcoercible
  2082. module.exports = function (it) {
  2083. if (isNullOrUndefined(it)) throw new $TypeError("Can't call method on " + it);
  2084. return it;
  2085. };
  2086. /***/ }),
  2087. /***/ 9286:
  2088. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2089. var SetHelpers = __webpack_require__(4402);
  2090. var iterate = __webpack_require__(8469);
  2091. var Set = SetHelpers.Set;
  2092. var add = SetHelpers.add;
  2093. module.exports = function (set) {
  2094. var result = new Set();
  2095. iterate(set, function (it) {
  2096. add(result, it);
  2097. });
  2098. return result;
  2099. };
  2100. /***/ }),
  2101. /***/ 3440:
  2102. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2103. var aSet = __webpack_require__(7080);
  2104. var SetHelpers = __webpack_require__(4402);
  2105. var clone = __webpack_require__(9286);
  2106. var size = __webpack_require__(5170);
  2107. var getSetRecord = __webpack_require__(3789);
  2108. var iterateSet = __webpack_require__(8469);
  2109. var iterateSimple = __webpack_require__(507);
  2110. var has = SetHelpers.has;
  2111. var remove = SetHelpers.remove;
  2112. // `Set.prototype.difference` method
  2113. // https://github.com/tc39/proposal-set-methods
  2114. module.exports = function difference(other) {
  2115. var O = aSet(this);
  2116. var otherRec = getSetRecord(other);
  2117. var result = clone(O);
  2118. if (size(O) <= otherRec.size) iterateSet(O, function (e) {
  2119. if (otherRec.includes(e)) remove(result, e);
  2120. });
  2121. else iterateSimple(otherRec.getIterator(), function (e) {
  2122. if (has(O, e)) remove(result, e);
  2123. });
  2124. return result;
  2125. };
  2126. /***/ }),
  2127. /***/ 4402:
  2128. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2129. var uncurryThis = __webpack_require__(9504);
  2130. // eslint-disable-next-line es/no-set -- safe
  2131. var SetPrototype = Set.prototype;
  2132. module.exports = {
  2133. // eslint-disable-next-line es/no-set -- safe
  2134. Set: Set,
  2135. add: uncurryThis(SetPrototype.add),
  2136. has: uncurryThis(SetPrototype.has),
  2137. remove: uncurryThis(SetPrototype['delete']),
  2138. proto: SetPrototype
  2139. };
  2140. /***/ }),
  2141. /***/ 8750:
  2142. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2143. var aSet = __webpack_require__(7080);
  2144. var SetHelpers = __webpack_require__(4402);
  2145. var size = __webpack_require__(5170);
  2146. var getSetRecord = __webpack_require__(3789);
  2147. var iterateSet = __webpack_require__(8469);
  2148. var iterateSimple = __webpack_require__(507);
  2149. var Set = SetHelpers.Set;
  2150. var add = SetHelpers.add;
  2151. var has = SetHelpers.has;
  2152. // `Set.prototype.intersection` method
  2153. // https://github.com/tc39/proposal-set-methods
  2154. module.exports = function intersection(other) {
  2155. var O = aSet(this);
  2156. var otherRec = getSetRecord(other);
  2157. var result = new Set();
  2158. if (size(O) > otherRec.size) {
  2159. iterateSimple(otherRec.getIterator(), function (e) {
  2160. if (has(O, e)) add(result, e);
  2161. });
  2162. } else {
  2163. iterateSet(O, function (e) {
  2164. if (otherRec.includes(e)) add(result, e);
  2165. });
  2166. }
  2167. return result;
  2168. };
  2169. /***/ }),
  2170. /***/ 4449:
  2171. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2172. var aSet = __webpack_require__(7080);
  2173. var has = (__webpack_require__(4402).has);
  2174. var size = __webpack_require__(5170);
  2175. var getSetRecord = __webpack_require__(3789);
  2176. var iterateSet = __webpack_require__(8469);
  2177. var iterateSimple = __webpack_require__(507);
  2178. var iteratorClose = __webpack_require__(9539);
  2179. // `Set.prototype.isDisjointFrom` method
  2180. // https://tc39.github.io/proposal-set-methods/#Set.prototype.isDisjointFrom
  2181. module.exports = function isDisjointFrom(other) {
  2182. var O = aSet(this);
  2183. var otherRec = getSetRecord(other);
  2184. if (size(O) <= otherRec.size) return iterateSet(O, function (e) {
  2185. if (otherRec.includes(e)) return false;
  2186. }, true) !== false;
  2187. var iterator = otherRec.getIterator();
  2188. return iterateSimple(iterator, function (e) {
  2189. if (has(O, e)) return iteratorClose(iterator, 'normal', false);
  2190. }) !== false;
  2191. };
  2192. /***/ }),
  2193. /***/ 3838:
  2194. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2195. var aSet = __webpack_require__(7080);
  2196. var size = __webpack_require__(5170);
  2197. var iterate = __webpack_require__(8469);
  2198. var getSetRecord = __webpack_require__(3789);
  2199. // `Set.prototype.isSubsetOf` method
  2200. // https://tc39.github.io/proposal-set-methods/#Set.prototype.isSubsetOf
  2201. module.exports = function isSubsetOf(other) {
  2202. var O = aSet(this);
  2203. var otherRec = getSetRecord(other);
  2204. if (size(O) > otherRec.size) return false;
  2205. return iterate(O, function (e) {
  2206. if (!otherRec.includes(e)) return false;
  2207. }, true) !== false;
  2208. };
  2209. /***/ }),
  2210. /***/ 8527:
  2211. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2212. var aSet = __webpack_require__(7080);
  2213. var has = (__webpack_require__(4402).has);
  2214. var size = __webpack_require__(5170);
  2215. var getSetRecord = __webpack_require__(3789);
  2216. var iterateSimple = __webpack_require__(507);
  2217. var iteratorClose = __webpack_require__(9539);
  2218. // `Set.prototype.isSupersetOf` method
  2219. // https://tc39.github.io/proposal-set-methods/#Set.prototype.isSupersetOf
  2220. module.exports = function isSupersetOf(other) {
  2221. var O = aSet(this);
  2222. var otherRec = getSetRecord(other);
  2223. if (size(O) < otherRec.size) return false;
  2224. var iterator = otherRec.getIterator();
  2225. return iterateSimple(iterator, function (e) {
  2226. if (!has(O, e)) return iteratorClose(iterator, 'normal', false);
  2227. }) !== false;
  2228. };
  2229. /***/ }),
  2230. /***/ 8469:
  2231. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2232. var uncurryThis = __webpack_require__(9504);
  2233. var iterateSimple = __webpack_require__(507);
  2234. var SetHelpers = __webpack_require__(4402);
  2235. var Set = SetHelpers.Set;
  2236. var SetPrototype = SetHelpers.proto;
  2237. var forEach = uncurryThis(SetPrototype.forEach);
  2238. var keys = uncurryThis(SetPrototype.keys);
  2239. var next = keys(new Set()).next;
  2240. module.exports = function (set, fn, interruptible) {
  2241. return interruptible ? iterateSimple({ iterator: keys(set), next: next }, fn) : forEach(set, fn);
  2242. };
  2243. /***/ }),
  2244. /***/ 4916:
  2245. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2246. var getBuiltIn = __webpack_require__(7751);
  2247. var createSetLike = function (size) {
  2248. return {
  2249. size: size,
  2250. has: function () {
  2251. return false;
  2252. },
  2253. keys: function () {
  2254. return {
  2255. next: function () {
  2256. return { done: true };
  2257. }
  2258. };
  2259. }
  2260. };
  2261. };
  2262. module.exports = function (name) {
  2263. var Set = getBuiltIn('Set');
  2264. try {
  2265. new Set()[name](createSetLike(0));
  2266. try {
  2267. // late spec change, early WebKit ~ Safari 17.0 beta implementation does not pass it
  2268. // https://github.com/tc39/proposal-set-methods/pull/88
  2269. new Set()[name](createSetLike(-1));
  2270. return false;
  2271. } catch (error2) {
  2272. return true;
  2273. }
  2274. } catch (error) {
  2275. return false;
  2276. }
  2277. };
  2278. /***/ }),
  2279. /***/ 5170:
  2280. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2281. var uncurryThisAccessor = __webpack_require__(6706);
  2282. var SetHelpers = __webpack_require__(4402);
  2283. module.exports = uncurryThisAccessor(SetHelpers.proto, 'size', 'get') || function (set) {
  2284. return set.size;
  2285. };
  2286. /***/ }),
  2287. /***/ 3650:
  2288. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2289. var aSet = __webpack_require__(7080);
  2290. var SetHelpers = __webpack_require__(4402);
  2291. var clone = __webpack_require__(9286);
  2292. var getSetRecord = __webpack_require__(3789);
  2293. var iterateSimple = __webpack_require__(507);
  2294. var add = SetHelpers.add;
  2295. var has = SetHelpers.has;
  2296. var remove = SetHelpers.remove;
  2297. // `Set.prototype.symmetricDifference` method
  2298. // https://github.com/tc39/proposal-set-methods
  2299. module.exports = function symmetricDifference(other) {
  2300. var O = aSet(this);
  2301. var keysIter = getSetRecord(other).getIterator();
  2302. var result = clone(O);
  2303. iterateSimple(keysIter, function (e) {
  2304. if (has(O, e)) remove(result, e);
  2305. else add(result, e);
  2306. });
  2307. return result;
  2308. };
  2309. /***/ }),
  2310. /***/ 4204:
  2311. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2312. var aSet = __webpack_require__(7080);
  2313. var add = (__webpack_require__(4402).add);
  2314. var clone = __webpack_require__(9286);
  2315. var getSetRecord = __webpack_require__(3789);
  2316. var iterateSimple = __webpack_require__(507);
  2317. // `Set.prototype.union` method
  2318. // https://github.com/tc39/proposal-set-methods
  2319. module.exports = function union(other) {
  2320. var O = aSet(this);
  2321. var keysIter = getSetRecord(other).getIterator();
  2322. var result = clone(O);
  2323. iterateSimple(keysIter, function (it) {
  2324. add(result, it);
  2325. });
  2326. return result;
  2327. };
  2328. /***/ }),
  2329. /***/ 6119:
  2330. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2331. var shared = __webpack_require__(5745);
  2332. var uid = __webpack_require__(3392);
  2333. var keys = shared('keys');
  2334. module.exports = function (key) {
  2335. return keys[key] || (keys[key] = uid(key));
  2336. };
  2337. /***/ }),
  2338. /***/ 7629:
  2339. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2340. var IS_PURE = __webpack_require__(6395);
  2341. var globalThis = __webpack_require__(4576);
  2342. var defineGlobalProperty = __webpack_require__(9433);
  2343. var SHARED = '__core-js_shared__';
  2344. var store = module.exports = globalThis[SHARED] || defineGlobalProperty(SHARED, {});
  2345. (store.versions || (store.versions = [])).push({
  2346. version: '3.38.1',
  2347. mode: IS_PURE ? 'pure' : 'global',
  2348. copyright: '© 2014-2024 Denis Pushkarev (zloirock.ru)',
  2349. license: 'https://github.com/zloirock/core-js/blob/v3.38.1/LICENSE',
  2350. source: 'https://github.com/zloirock/core-js'
  2351. });
  2352. /***/ }),
  2353. /***/ 5745:
  2354. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2355. var store = __webpack_require__(7629);
  2356. module.exports = function (key, value) {
  2357. return store[key] || (store[key] = value || {});
  2358. };
  2359. /***/ }),
  2360. /***/ 1548:
  2361. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2362. var globalThis = __webpack_require__(4576);
  2363. var fails = __webpack_require__(9039);
  2364. var V8 = __webpack_require__(9519);
  2365. var ENVIRONMENT = __webpack_require__(4215);
  2366. var structuredClone = globalThis.structuredClone;
  2367. module.exports = !!structuredClone && !fails(function () {
  2368. // prevent V8 ArrayBufferDetaching protector cell invalidation and performance degradation
  2369. // https://github.com/zloirock/core-js/issues/679
  2370. if ((ENVIRONMENT === 'DENO' && V8 > 92) || (ENVIRONMENT === 'NODE' && V8 > 94) || (ENVIRONMENT === 'BROWSER' && V8 > 97)) return false;
  2371. var buffer = new ArrayBuffer(8);
  2372. var clone = structuredClone(buffer, { transfer: [buffer] });
  2373. return buffer.byteLength !== 0 || clone.byteLength !== 8;
  2374. });
  2375. /***/ }),
  2376. /***/ 4495:
  2377. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2378. /* eslint-disable es/no-symbol -- required for testing */
  2379. var V8_VERSION = __webpack_require__(9519);
  2380. var fails = __webpack_require__(9039);
  2381. var globalThis = __webpack_require__(4576);
  2382. var $String = globalThis.String;
  2383. // eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing
  2384. module.exports = !!Object.getOwnPropertySymbols && !fails(function () {
  2385. var symbol = Symbol('symbol detection');
  2386. // Chrome 38 Symbol has incorrect toString conversion
  2387. // `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances
  2388. // nb: Do not call `String` directly to avoid this being optimized out to `symbol+''` which will,
  2389. // of course, fail.
  2390. return !$String(symbol) || !(Object(symbol) instanceof Symbol) ||
  2391. // Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances
  2392. !Symbol.sham && V8_VERSION && V8_VERSION < 41;
  2393. });
  2394. /***/ }),
  2395. /***/ 5610:
  2396. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2397. var toIntegerOrInfinity = __webpack_require__(1291);
  2398. var max = Math.max;
  2399. var min = Math.min;
  2400. // Helper for a popular repeating case of the spec:
  2401. // Let integer be ? ToInteger(index).
  2402. // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
  2403. module.exports = function (index, length) {
  2404. var integer = toIntegerOrInfinity(index);
  2405. return integer < 0 ? max(integer + length, 0) : min(integer, length);
  2406. };
  2407. /***/ }),
  2408. /***/ 5854:
  2409. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2410. var toPrimitive = __webpack_require__(2777);
  2411. var $TypeError = TypeError;
  2412. // `ToBigInt` abstract operation
  2413. // https://tc39.es/ecma262/#sec-tobigint
  2414. module.exports = function (argument) {
  2415. var prim = toPrimitive(argument, 'number');
  2416. if (typeof prim == 'number') throw new $TypeError("Can't convert number to bigint");
  2417. // eslint-disable-next-line es/no-bigint -- safe
  2418. return BigInt(prim);
  2419. };
  2420. /***/ }),
  2421. /***/ 7696:
  2422. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2423. var toIntegerOrInfinity = __webpack_require__(1291);
  2424. var toLength = __webpack_require__(8014);
  2425. var $RangeError = RangeError;
  2426. // `ToIndex` abstract operation
  2427. // https://tc39.es/ecma262/#sec-toindex
  2428. module.exports = function (it) {
  2429. if (it === undefined) return 0;
  2430. var number = toIntegerOrInfinity(it);
  2431. var length = toLength(number);
  2432. if (number !== length) throw new $RangeError('Wrong length or index');
  2433. return length;
  2434. };
  2435. /***/ }),
  2436. /***/ 5397:
  2437. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2438. // toObject with fallback for non-array-like ES3 strings
  2439. var IndexedObject = __webpack_require__(7055);
  2440. var requireObjectCoercible = __webpack_require__(7750);
  2441. module.exports = function (it) {
  2442. return IndexedObject(requireObjectCoercible(it));
  2443. };
  2444. /***/ }),
  2445. /***/ 1291:
  2446. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2447. var trunc = __webpack_require__(741);
  2448. // `ToIntegerOrInfinity` abstract operation
  2449. // https://tc39.es/ecma262/#sec-tointegerorinfinity
  2450. module.exports = function (argument) {
  2451. var number = +argument;
  2452. // eslint-disable-next-line no-self-compare -- NaN check
  2453. return number !== number || number === 0 ? 0 : trunc(number);
  2454. };
  2455. /***/ }),
  2456. /***/ 8014:
  2457. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2458. var toIntegerOrInfinity = __webpack_require__(1291);
  2459. var min = Math.min;
  2460. // `ToLength` abstract operation
  2461. // https://tc39.es/ecma262/#sec-tolength
  2462. module.exports = function (argument) {
  2463. var len = toIntegerOrInfinity(argument);
  2464. return len > 0 ? min(len, 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
  2465. };
  2466. /***/ }),
  2467. /***/ 8981:
  2468. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2469. var requireObjectCoercible = __webpack_require__(7750);
  2470. var $Object = Object;
  2471. // `ToObject` abstract operation
  2472. // https://tc39.es/ecma262/#sec-toobject
  2473. module.exports = function (argument) {
  2474. return $Object(requireObjectCoercible(argument));
  2475. };
  2476. /***/ }),
  2477. /***/ 9590:
  2478. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2479. var toIntegerOrInfinity = __webpack_require__(1291);
  2480. var $RangeError = RangeError;
  2481. module.exports = function (it) {
  2482. var result = toIntegerOrInfinity(it);
  2483. if (result < 0) throw new $RangeError("The argument can't be less than 0");
  2484. return result;
  2485. };
  2486. /***/ }),
  2487. /***/ 2777:
  2488. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2489. var call = __webpack_require__(9565);
  2490. var isObject = __webpack_require__(34);
  2491. var isSymbol = __webpack_require__(757);
  2492. var getMethod = __webpack_require__(5966);
  2493. var ordinaryToPrimitive = __webpack_require__(4270);
  2494. var wellKnownSymbol = __webpack_require__(8227);
  2495. var $TypeError = TypeError;
  2496. var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
  2497. // `ToPrimitive` abstract operation
  2498. // https://tc39.es/ecma262/#sec-toprimitive
  2499. module.exports = function (input, pref) {
  2500. if (!isObject(input) || isSymbol(input)) return input;
  2501. var exoticToPrim = getMethod(input, TO_PRIMITIVE);
  2502. var result;
  2503. if (exoticToPrim) {
  2504. if (pref === undefined) pref = 'default';
  2505. result = call(exoticToPrim, input, pref);
  2506. if (!isObject(result) || isSymbol(result)) return result;
  2507. throw new $TypeError("Can't convert object to primitive value");
  2508. }
  2509. if (pref === undefined) pref = 'number';
  2510. return ordinaryToPrimitive(input, pref);
  2511. };
  2512. /***/ }),
  2513. /***/ 6969:
  2514. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2515. var toPrimitive = __webpack_require__(2777);
  2516. var isSymbol = __webpack_require__(757);
  2517. // `ToPropertyKey` abstract operation
  2518. // https://tc39.es/ecma262/#sec-topropertykey
  2519. module.exports = function (argument) {
  2520. var key = toPrimitive(argument, 'string');
  2521. return isSymbol(key) ? key : key + '';
  2522. };
  2523. /***/ }),
  2524. /***/ 2140:
  2525. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2526. var wellKnownSymbol = __webpack_require__(8227);
  2527. var TO_STRING_TAG = wellKnownSymbol('toStringTag');
  2528. var test = {};
  2529. test[TO_STRING_TAG] = 'z';
  2530. module.exports = String(test) === '[object z]';
  2531. /***/ }),
  2532. /***/ 655:
  2533. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2534. var classof = __webpack_require__(6955);
  2535. var $String = String;
  2536. module.exports = function (argument) {
  2537. if (classof(argument) === 'Symbol') throw new TypeError('Cannot convert a Symbol value to a string');
  2538. return $String(argument);
  2539. };
  2540. /***/ }),
  2541. /***/ 6823:
  2542. /***/ ((module) => {
  2543. var $String = String;
  2544. module.exports = function (argument) {
  2545. try {
  2546. return $String(argument);
  2547. } catch (error) {
  2548. return 'Object';
  2549. }
  2550. };
  2551. /***/ }),
  2552. /***/ 3392:
  2553. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2554. var uncurryThis = __webpack_require__(9504);
  2555. var id = 0;
  2556. var postfix = Math.random();
  2557. var toString = uncurryThis(1.0.toString);
  2558. module.exports = function (key) {
  2559. return 'Symbol(' + (key === undefined ? '' : key) + ')_' + toString(++id + postfix, 36);
  2560. };
  2561. /***/ }),
  2562. /***/ 7040:
  2563. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2564. /* eslint-disable es/no-symbol -- required for testing */
  2565. var NATIVE_SYMBOL = __webpack_require__(4495);
  2566. module.exports = NATIVE_SYMBOL
  2567. && !Symbol.sham
  2568. && typeof Symbol.iterator == 'symbol';
  2569. /***/ }),
  2570. /***/ 8686:
  2571. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2572. var DESCRIPTORS = __webpack_require__(3724);
  2573. var fails = __webpack_require__(9039);
  2574. // V8 ~ Chrome 36-
  2575. // https://bugs.chromium.org/p/v8/issues/detail?id=3334
  2576. module.exports = DESCRIPTORS && fails(function () {
  2577. // eslint-disable-next-line es/no-object-defineproperty -- required for testing
  2578. return Object.defineProperty(function () { /* empty */ }, 'prototype', {
  2579. value: 42,
  2580. writable: false
  2581. }).prototype !== 42;
  2582. });
  2583. /***/ }),
  2584. /***/ 2812:
  2585. /***/ ((module) => {
  2586. var $TypeError = TypeError;
  2587. module.exports = function (passed, required) {
  2588. if (passed < required) throw new $TypeError('Not enough arguments');
  2589. return passed;
  2590. };
  2591. /***/ }),
  2592. /***/ 8622:
  2593. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2594. var globalThis = __webpack_require__(4576);
  2595. var isCallable = __webpack_require__(4901);
  2596. var WeakMap = globalThis.WeakMap;
  2597. module.exports = isCallable(WeakMap) && /native code/.test(String(WeakMap));
  2598. /***/ }),
  2599. /***/ 8227:
  2600. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2601. var globalThis = __webpack_require__(4576);
  2602. var shared = __webpack_require__(5745);
  2603. var hasOwn = __webpack_require__(9297);
  2604. var uid = __webpack_require__(3392);
  2605. var NATIVE_SYMBOL = __webpack_require__(4495);
  2606. var USE_SYMBOL_AS_UID = __webpack_require__(7040);
  2607. var Symbol = globalThis.Symbol;
  2608. var WellKnownSymbolsStore = shared('wks');
  2609. var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol['for'] || Symbol : Symbol && Symbol.withoutSetter || uid;
  2610. module.exports = function (name) {
  2611. if (!hasOwn(WellKnownSymbolsStore, name)) {
  2612. WellKnownSymbolsStore[name] = NATIVE_SYMBOL && hasOwn(Symbol, name)
  2613. ? Symbol[name]
  2614. : createWellKnownSymbol('Symbol.' + name);
  2615. } return WellKnownSymbolsStore[name];
  2616. };
  2617. /***/ }),
  2618. /***/ 6573:
  2619. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2620. var DESCRIPTORS = __webpack_require__(3724);
  2621. var defineBuiltInAccessor = __webpack_require__(2106);
  2622. var isDetached = __webpack_require__(3238);
  2623. var ArrayBufferPrototype = ArrayBuffer.prototype;
  2624. if (DESCRIPTORS && !('detached' in ArrayBufferPrototype)) {
  2625. defineBuiltInAccessor(ArrayBufferPrototype, 'detached', {
  2626. configurable: true,
  2627. get: function detached() {
  2628. return isDetached(this);
  2629. }
  2630. });
  2631. }
  2632. /***/ }),
  2633. /***/ 7936:
  2634. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2635. var $ = __webpack_require__(6518);
  2636. var $transfer = __webpack_require__(5636);
  2637. // `ArrayBuffer.prototype.transferToFixedLength` method
  2638. // https://tc39.es/proposal-arraybuffer-transfer/#sec-arraybuffer.prototype.transfertofixedlength
  2639. if ($transfer) $({ target: 'ArrayBuffer', proto: true }, {
  2640. transferToFixedLength: function transferToFixedLength() {
  2641. return $transfer(this, arguments.length ? arguments[0] : undefined, false);
  2642. }
  2643. });
  2644. /***/ }),
  2645. /***/ 8100:
  2646. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2647. var $ = __webpack_require__(6518);
  2648. var $transfer = __webpack_require__(5636);
  2649. // `ArrayBuffer.prototype.transfer` method
  2650. // https://tc39.es/proposal-arraybuffer-transfer/#sec-arraybuffer.prototype.transfer
  2651. if ($transfer) $({ target: 'ArrayBuffer', proto: true }, {
  2652. transfer: function transfer() {
  2653. return $transfer(this, arguments.length ? arguments[0] : undefined, true);
  2654. }
  2655. });
  2656. /***/ }),
  2657. /***/ 4114:
  2658. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2659. var $ = __webpack_require__(6518);
  2660. var toObject = __webpack_require__(8981);
  2661. var lengthOfArrayLike = __webpack_require__(6198);
  2662. var setArrayLength = __webpack_require__(4527);
  2663. var doesNotExceedSafeInteger = __webpack_require__(6837);
  2664. var fails = __webpack_require__(9039);
  2665. var INCORRECT_TO_LENGTH = fails(function () {
  2666. return [].push.call({ length: 0x100000000 }, 1) !== 4294967297;
  2667. });
  2668. // V8 <= 121 and Safari <= 15.4; FF < 23 throws InternalError
  2669. // https://bugs.chromium.org/p/v8/issues/detail?id=12681
  2670. var properErrorOnNonWritableLength = function () {
  2671. try {
  2672. // eslint-disable-next-line es/no-object-defineproperty -- safe
  2673. Object.defineProperty([], 'length', { writable: false }).push();
  2674. } catch (error) {
  2675. return error instanceof TypeError;
  2676. }
  2677. };
  2678. var FORCED = INCORRECT_TO_LENGTH || !properErrorOnNonWritableLength();
  2679. // `Array.prototype.push` method
  2680. // https://tc39.es/ecma262/#sec-array.prototype.push
  2681. $({ target: 'Array', proto: true, arity: 1, forced: FORCED }, {
  2682. // eslint-disable-next-line no-unused-vars -- required for `.length`
  2683. push: function push(item) {
  2684. var O = toObject(this);
  2685. var len = lengthOfArrayLike(O);
  2686. var argCount = arguments.length;
  2687. doesNotExceedSafeInteger(len + argCount);
  2688. for (var i = 0; i < argCount; i++) {
  2689. O[len] = arguments[i];
  2690. len++;
  2691. }
  2692. setArrayLength(O, len);
  2693. return len;
  2694. }
  2695. });
  2696. /***/ }),
  2697. /***/ 4628:
  2698. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2699. var $ = __webpack_require__(6518);
  2700. var newPromiseCapabilityModule = __webpack_require__(6043);
  2701. // `Promise.withResolvers` method
  2702. // https://github.com/tc39/proposal-promise-with-resolvers
  2703. $({ target: 'Promise', stat: true }, {
  2704. withResolvers: function withResolvers() {
  2705. var promiseCapability = newPromiseCapabilityModule.f(this);
  2706. return {
  2707. promise: promiseCapability.promise,
  2708. resolve: promiseCapability.resolve,
  2709. reject: promiseCapability.reject
  2710. };
  2711. }
  2712. });
  2713. /***/ }),
  2714. /***/ 7642:
  2715. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2716. var $ = __webpack_require__(6518);
  2717. var difference = __webpack_require__(3440);
  2718. var setMethodAcceptSetLike = __webpack_require__(4916);
  2719. // `Set.prototype.difference` method
  2720. // https://github.com/tc39/proposal-set-methods
  2721. $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('difference') }, {
  2722. difference: difference
  2723. });
  2724. /***/ }),
  2725. /***/ 8004:
  2726. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2727. var $ = __webpack_require__(6518);
  2728. var fails = __webpack_require__(9039);
  2729. var intersection = __webpack_require__(8750);
  2730. var setMethodAcceptSetLike = __webpack_require__(4916);
  2731. var INCORRECT = !setMethodAcceptSetLike('intersection') || fails(function () {
  2732. // eslint-disable-next-line es/no-array-from, es/no-set -- testing
  2733. return String(Array.from(new Set([1, 2, 3]).intersection(new Set([3, 2])))) !== '3,2';
  2734. });
  2735. // `Set.prototype.intersection` method
  2736. // https://github.com/tc39/proposal-set-methods
  2737. $({ target: 'Set', proto: true, real: true, forced: INCORRECT }, {
  2738. intersection: intersection
  2739. });
  2740. /***/ }),
  2741. /***/ 3853:
  2742. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2743. var $ = __webpack_require__(6518);
  2744. var isDisjointFrom = __webpack_require__(4449);
  2745. var setMethodAcceptSetLike = __webpack_require__(4916);
  2746. // `Set.prototype.isDisjointFrom` method
  2747. // https://github.com/tc39/proposal-set-methods
  2748. $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isDisjointFrom') }, {
  2749. isDisjointFrom: isDisjointFrom
  2750. });
  2751. /***/ }),
  2752. /***/ 5876:
  2753. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2754. var $ = __webpack_require__(6518);
  2755. var isSubsetOf = __webpack_require__(3838);
  2756. var setMethodAcceptSetLike = __webpack_require__(4916);
  2757. // `Set.prototype.isSubsetOf` method
  2758. // https://github.com/tc39/proposal-set-methods
  2759. $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isSubsetOf') }, {
  2760. isSubsetOf: isSubsetOf
  2761. });
  2762. /***/ }),
  2763. /***/ 2475:
  2764. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2765. var $ = __webpack_require__(6518);
  2766. var isSupersetOf = __webpack_require__(8527);
  2767. var setMethodAcceptSetLike = __webpack_require__(4916);
  2768. // `Set.prototype.isSupersetOf` method
  2769. // https://github.com/tc39/proposal-set-methods
  2770. $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isSupersetOf') }, {
  2771. isSupersetOf: isSupersetOf
  2772. });
  2773. /***/ }),
  2774. /***/ 5024:
  2775. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2776. var $ = __webpack_require__(6518);
  2777. var symmetricDifference = __webpack_require__(3650);
  2778. var setMethodAcceptSetLike = __webpack_require__(4916);
  2779. // `Set.prototype.symmetricDifference` method
  2780. // https://github.com/tc39/proposal-set-methods
  2781. $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('symmetricDifference') }, {
  2782. symmetricDifference: symmetricDifference
  2783. });
  2784. /***/ }),
  2785. /***/ 1698:
  2786. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2787. var $ = __webpack_require__(6518);
  2788. var union = __webpack_require__(4204);
  2789. var setMethodAcceptSetLike = __webpack_require__(4916);
  2790. // `Set.prototype.union` method
  2791. // https://github.com/tc39/proposal-set-methods
  2792. $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('union') }, {
  2793. union: union
  2794. });
  2795. /***/ }),
  2796. /***/ 7467:
  2797. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2798. var arrayToReversed = __webpack_require__(7628);
  2799. var ArrayBufferViewCore = __webpack_require__(4644);
  2800. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  2801. var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;
  2802. var getTypedArrayConstructor = ArrayBufferViewCore.getTypedArrayConstructor;
  2803. // `%TypedArray%.prototype.toReversed` method
  2804. // https://tc39.es/ecma262/#sec-%typedarray%.prototype.toreversed
  2805. exportTypedArrayMethod('toReversed', function toReversed() {
  2806. return arrayToReversed(aTypedArray(this), getTypedArrayConstructor(this));
  2807. });
  2808. /***/ }),
  2809. /***/ 4732:
  2810. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2811. var ArrayBufferViewCore = __webpack_require__(4644);
  2812. var uncurryThis = __webpack_require__(9504);
  2813. var aCallable = __webpack_require__(9306);
  2814. var arrayFromConstructorAndList = __webpack_require__(5370);
  2815. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  2816. var getTypedArrayConstructor = ArrayBufferViewCore.getTypedArrayConstructor;
  2817. var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;
  2818. var sort = uncurryThis(ArrayBufferViewCore.TypedArrayPrototype.sort);
  2819. // `%TypedArray%.prototype.toSorted` method
  2820. // https://tc39.es/ecma262/#sec-%typedarray%.prototype.tosorted
  2821. exportTypedArrayMethod('toSorted', function toSorted(compareFn) {
  2822. if (compareFn !== undefined) aCallable(compareFn);
  2823. var O = aTypedArray(this);
  2824. var A = arrayFromConstructorAndList(getTypedArrayConstructor(O), O);
  2825. return sort(A, compareFn);
  2826. });
  2827. /***/ }),
  2828. /***/ 9577:
  2829. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2830. var arrayWith = __webpack_require__(9928);
  2831. var ArrayBufferViewCore = __webpack_require__(4644);
  2832. var isBigIntArray = __webpack_require__(1108);
  2833. var toIntegerOrInfinity = __webpack_require__(1291);
  2834. var toBigInt = __webpack_require__(5854);
  2835. var aTypedArray = ArrayBufferViewCore.aTypedArray;
  2836. var getTypedArrayConstructor = ArrayBufferViewCore.getTypedArrayConstructor;
  2837. var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;
  2838. var PROPER_ORDER = !!function () {
  2839. try {
  2840. // eslint-disable-next-line no-throw-literal, es/no-typed-arrays, es/no-array-prototype-with -- required for testing
  2841. new Int8Array(1)['with'](2, { valueOf: function () { throw 8; } });
  2842. } catch (error) {
  2843. // some early implementations, like WebKit, does not follow the final semantic
  2844. // https://github.com/tc39/proposal-change-array-by-copy/pull/86
  2845. return error === 8;
  2846. }
  2847. }();
  2848. // `%TypedArray%.prototype.with` method
  2849. // https://tc39.es/ecma262/#sec-%typedarray%.prototype.with
  2850. exportTypedArrayMethod('with', { 'with': function (index, value) {
  2851. var O = aTypedArray(this);
  2852. var relativeIndex = toIntegerOrInfinity(index);
  2853. var actualValue = isBigIntArray(O) ? toBigInt(value) : +value;
  2854. return arrayWith(O, getTypedArrayConstructor(O), relativeIndex, actualValue);
  2855. } }['with'], !PROPER_ORDER);
  2856. /***/ }),
  2857. /***/ 8992:
  2858. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2859. var $ = __webpack_require__(6518);
  2860. var globalThis = __webpack_require__(4576);
  2861. var anInstance = __webpack_require__(679);
  2862. var anObject = __webpack_require__(8551);
  2863. var isCallable = __webpack_require__(4901);
  2864. var getPrototypeOf = __webpack_require__(2787);
  2865. var defineBuiltInAccessor = __webpack_require__(2106);
  2866. var createProperty = __webpack_require__(4659);
  2867. var fails = __webpack_require__(9039);
  2868. var hasOwn = __webpack_require__(9297);
  2869. var wellKnownSymbol = __webpack_require__(8227);
  2870. var IteratorPrototype = (__webpack_require__(7657).IteratorPrototype);
  2871. var DESCRIPTORS = __webpack_require__(3724);
  2872. var IS_PURE = __webpack_require__(6395);
  2873. var CONSTRUCTOR = 'constructor';
  2874. var ITERATOR = 'Iterator';
  2875. var TO_STRING_TAG = wellKnownSymbol('toStringTag');
  2876. var $TypeError = TypeError;
  2877. var NativeIterator = globalThis[ITERATOR];
  2878. // FF56- have non-standard global helper `Iterator`
  2879. var FORCED = IS_PURE
  2880. || !isCallable(NativeIterator)
  2881. || NativeIterator.prototype !== IteratorPrototype
  2882. // FF44- non-standard `Iterator` passes previous tests
  2883. || !fails(function () { NativeIterator({}); });
  2884. var IteratorConstructor = function Iterator() {
  2885. anInstance(this, IteratorPrototype);
  2886. if (getPrototypeOf(this) === IteratorPrototype) throw new $TypeError('Abstract class Iterator not directly constructable');
  2887. };
  2888. var defineIteratorPrototypeAccessor = function (key, value) {
  2889. if (DESCRIPTORS) {
  2890. defineBuiltInAccessor(IteratorPrototype, key, {
  2891. configurable: true,
  2892. get: function () {
  2893. return value;
  2894. },
  2895. set: function (replacement) {
  2896. anObject(this);
  2897. if (this === IteratorPrototype) throw new $TypeError("You can't redefine this property");
  2898. if (hasOwn(this, key)) this[key] = replacement;
  2899. else createProperty(this, key, replacement);
  2900. }
  2901. });
  2902. } else IteratorPrototype[key] = value;
  2903. };
  2904. if (!hasOwn(IteratorPrototype, TO_STRING_TAG)) defineIteratorPrototypeAccessor(TO_STRING_TAG, ITERATOR);
  2905. if (FORCED || !hasOwn(IteratorPrototype, CONSTRUCTOR) || IteratorPrototype[CONSTRUCTOR] === Object) {
  2906. defineIteratorPrototypeAccessor(CONSTRUCTOR, IteratorConstructor);
  2907. }
  2908. IteratorConstructor.prototype = IteratorPrototype;
  2909. // `Iterator` constructor
  2910. // https://github.com/tc39/proposal-iterator-helpers
  2911. $({ global: true, constructor: true, forced: FORCED }, {
  2912. Iterator: IteratorConstructor
  2913. });
  2914. /***/ }),
  2915. /***/ 4743:
  2916. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2917. var $ = __webpack_require__(6518);
  2918. var call = __webpack_require__(9565);
  2919. var anObject = __webpack_require__(8551);
  2920. var getIteratorDirect = __webpack_require__(1767);
  2921. var notANaN = __webpack_require__(4149);
  2922. var toPositiveInteger = __webpack_require__(9590);
  2923. var createIteratorProxy = __webpack_require__(9462);
  2924. var IS_PURE = __webpack_require__(6395);
  2925. var IteratorProxy = createIteratorProxy(function () {
  2926. var iterator = this.iterator;
  2927. var next = this.next;
  2928. var result, done;
  2929. while (this.remaining) {
  2930. this.remaining--;
  2931. result = anObject(call(next, iterator));
  2932. done = this.done = !!result.done;
  2933. if (done) return;
  2934. }
  2935. result = anObject(call(next, iterator));
  2936. done = this.done = !!result.done;
  2937. if (!done) return result.value;
  2938. });
  2939. // `Iterator.prototype.drop` method
  2940. // https://github.com/tc39/proposal-iterator-helpers
  2941. $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE }, {
  2942. drop: function drop(limit) {
  2943. anObject(this);
  2944. var remaining = toPositiveInteger(notANaN(+limit));
  2945. return new IteratorProxy(getIteratorDirect(this), {
  2946. remaining: remaining
  2947. });
  2948. }
  2949. });
  2950. /***/ }),
  2951. /***/ 3215:
  2952. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2953. var $ = __webpack_require__(6518);
  2954. var iterate = __webpack_require__(2652);
  2955. var aCallable = __webpack_require__(9306);
  2956. var anObject = __webpack_require__(8551);
  2957. var getIteratorDirect = __webpack_require__(1767);
  2958. // `Iterator.prototype.every` method
  2959. // https://github.com/tc39/proposal-iterator-helpers
  2960. $({ target: 'Iterator', proto: true, real: true }, {
  2961. every: function every(predicate) {
  2962. anObject(this);
  2963. aCallable(predicate);
  2964. var record = getIteratorDirect(this);
  2965. var counter = 0;
  2966. return !iterate(record, function (value, stop) {
  2967. if (!predicate(value, counter++)) return stop();
  2968. }, { IS_RECORD: true, INTERRUPTED: true }).stopped;
  2969. }
  2970. });
  2971. /***/ }),
  2972. /***/ 4520:
  2973. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  2974. var $ = __webpack_require__(6518);
  2975. var call = __webpack_require__(9565);
  2976. var aCallable = __webpack_require__(9306);
  2977. var anObject = __webpack_require__(8551);
  2978. var getIteratorDirect = __webpack_require__(1767);
  2979. var createIteratorProxy = __webpack_require__(9462);
  2980. var callWithSafeIterationClosing = __webpack_require__(6319);
  2981. var IS_PURE = __webpack_require__(6395);
  2982. var IteratorProxy = createIteratorProxy(function () {
  2983. var iterator = this.iterator;
  2984. var predicate = this.predicate;
  2985. var next = this.next;
  2986. var result, done, value;
  2987. while (true) {
  2988. result = anObject(call(next, iterator));
  2989. done = this.done = !!result.done;
  2990. if (done) return;
  2991. value = result.value;
  2992. if (callWithSafeIterationClosing(iterator, predicate, [value, this.counter++], true)) return value;
  2993. }
  2994. });
  2995. // `Iterator.prototype.filter` method
  2996. // https://github.com/tc39/proposal-iterator-helpers
  2997. $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE }, {
  2998. filter: function filter(predicate) {
  2999. anObject(this);
  3000. aCallable(predicate);
  3001. return new IteratorProxy(getIteratorDirect(this), {
  3002. predicate: predicate
  3003. });
  3004. }
  3005. });
  3006. /***/ }),
  3007. /***/ 670:
  3008. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  3009. var $ = __webpack_require__(6518);
  3010. var call = __webpack_require__(9565);
  3011. var aCallable = __webpack_require__(9306);
  3012. var anObject = __webpack_require__(8551);
  3013. var getIteratorDirect = __webpack_require__(1767);
  3014. var getIteratorFlattenable = __webpack_require__(8646);
  3015. var createIteratorProxy = __webpack_require__(9462);
  3016. var iteratorClose = __webpack_require__(9539);
  3017. var IS_PURE = __webpack_require__(6395);
  3018. var IteratorProxy = createIteratorProxy(function () {
  3019. var iterator = this.iterator;
  3020. var mapper = this.mapper;
  3021. var result, inner;
  3022. while (true) {
  3023. if (inner = this.inner) try {
  3024. result = anObject(call(inner.next, inner.iterator));
  3025. if (!result.done) return result.value;
  3026. this.inner = null;
  3027. } catch (error) { iteratorClose(iterator, 'throw', error); }
  3028. result = anObject(call(this.next, iterator));
  3029. if (this.done = !!result.done) return;
  3030. try {
  3031. this.inner = getIteratorFlattenable(mapper(result.value, this.counter++), false);
  3032. } catch (error) { iteratorClose(iterator, 'throw', error); }
  3033. }
  3034. });
  3035. // `Iterator.prototype.flatMap` method
  3036. // https://github.com/tc39/proposal-iterator-helpers
  3037. $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE }, {
  3038. flatMap: function flatMap(mapper) {
  3039. anObject(this);
  3040. aCallable(mapper);
  3041. return new IteratorProxy(getIteratorDirect(this), {
  3042. mapper: mapper,
  3043. inner: null
  3044. });
  3045. }
  3046. });
  3047. /***/ }),
  3048. /***/ 1454:
  3049. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  3050. var $ = __webpack_require__(6518);
  3051. var map = __webpack_require__(713);
  3052. var IS_PURE = __webpack_require__(6395);
  3053. // `Iterator.prototype.map` method
  3054. // https://github.com/tc39/proposal-iterator-helpers
  3055. $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE }, {
  3056. map: map
  3057. });
  3058. /***/ }),
  3059. /***/ 7550:
  3060. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  3061. var $ = __webpack_require__(6518);
  3062. var iterate = __webpack_require__(2652);
  3063. var aCallable = __webpack_require__(9306);
  3064. var anObject = __webpack_require__(8551);
  3065. var getIteratorDirect = __webpack_require__(1767);
  3066. // `Iterator.prototype.some` method
  3067. // https://github.com/tc39/proposal-iterator-helpers
  3068. $({ target: 'Iterator', proto: true, real: true }, {
  3069. some: function some(predicate) {
  3070. anObject(this);
  3071. aCallable(predicate);
  3072. var record = getIteratorDirect(this);
  3073. var counter = 0;
  3074. return iterate(record, function (value, stop) {
  3075. if (predicate(value, counter++)) return stop();
  3076. }, { IS_RECORD: true, INTERRUPTED: true }).stopped;
  3077. }
  3078. });
  3079. /***/ }),
  3080. /***/ 8335:
  3081. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  3082. var $ = __webpack_require__(6518);
  3083. var DESCRIPTORS = __webpack_require__(3724);
  3084. var globalThis = __webpack_require__(4576);
  3085. var getBuiltIn = __webpack_require__(7751);
  3086. var uncurryThis = __webpack_require__(9504);
  3087. var call = __webpack_require__(9565);
  3088. var isCallable = __webpack_require__(4901);
  3089. var isObject = __webpack_require__(34);
  3090. var isArray = __webpack_require__(4376);
  3091. var hasOwn = __webpack_require__(9297);
  3092. var toString = __webpack_require__(655);
  3093. var lengthOfArrayLike = __webpack_require__(6198);
  3094. var createProperty = __webpack_require__(4659);
  3095. var fails = __webpack_require__(9039);
  3096. var parseJSONString = __webpack_require__(8235);
  3097. var NATIVE_SYMBOL = __webpack_require__(4495);
  3098. var JSON = globalThis.JSON;
  3099. var Number = globalThis.Number;
  3100. var SyntaxError = globalThis.SyntaxError;
  3101. var nativeParse = JSON && JSON.parse;
  3102. var enumerableOwnProperties = getBuiltIn('Object', 'keys');
  3103. // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
  3104. var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  3105. var at = uncurryThis(''.charAt);
  3106. var slice = uncurryThis(''.slice);
  3107. var exec = uncurryThis(/./.exec);
  3108. var push = uncurryThis([].push);
  3109. var IS_DIGIT = /^\d$/;
  3110. var IS_NON_ZERO_DIGIT = /^[1-9]$/;
  3111. var IS_NUMBER_START = /^[\d-]$/;
  3112. var IS_WHITESPACE = /^[\t\n\r ]$/;
  3113. var PRIMITIVE = 0;
  3114. var OBJECT = 1;
  3115. var $parse = function (source, reviver) {
  3116. source = toString(source);
  3117. var context = new Context(source, 0, '');
  3118. var root = context.parse();
  3119. var value = root.value;
  3120. var endIndex = context.skip(IS_WHITESPACE, root.end);
  3121. if (endIndex < source.length) {
  3122. throw new SyntaxError('Unexpected extra character: "' + at(source, endIndex) + '" after the parsed data at: ' + endIndex);
  3123. }
  3124. return isCallable(reviver) ? internalize({ '': value }, '', reviver, root) : value;
  3125. };
  3126. var internalize = function (holder, name, reviver, node) {
  3127. var val = holder[name];
  3128. var unmodified = node && val === node.value;
  3129. var context = unmodified && typeof node.source == 'string' ? { source: node.source } : {};
  3130. var elementRecordsLen, keys, len, i, P;
  3131. if (isObject(val)) {
  3132. var nodeIsArray = isArray(val);
  3133. var nodes = unmodified ? node.nodes : nodeIsArray ? [] : {};
  3134. if (nodeIsArray) {
  3135. elementRecordsLen = nodes.length;
  3136. len = lengthOfArrayLike(val);
  3137. for (i = 0; i < len; i++) {
  3138. internalizeProperty(val, i, internalize(val, '' + i, reviver, i < elementRecordsLen ? nodes[i] : undefined));
  3139. }
  3140. } else {
  3141. keys = enumerableOwnProperties(val);
  3142. len = lengthOfArrayLike(keys);
  3143. for (i = 0; i < len; i++) {
  3144. P = keys[i];
  3145. internalizeProperty(val, P, internalize(val, P, reviver, hasOwn(nodes, P) ? nodes[P] : undefined));
  3146. }
  3147. }
  3148. }
  3149. return call(reviver, holder, name, val, context);
  3150. };
  3151. var internalizeProperty = function (object, key, value) {
  3152. if (DESCRIPTORS) {
  3153. var descriptor = getOwnPropertyDescriptor(object, key);
  3154. if (descriptor && !descriptor.configurable) return;
  3155. }
  3156. if (value === undefined) delete object[key];
  3157. else createProperty(object, key, value);
  3158. };
  3159. var Node = function (value, end, source, nodes) {
  3160. this.value = value;
  3161. this.end = end;
  3162. this.source = source;
  3163. this.nodes = nodes;
  3164. };
  3165. var Context = function (source, index) {
  3166. this.source = source;
  3167. this.index = index;
  3168. };
  3169. // https://www.json.org/json-en.html
  3170. Context.prototype = {
  3171. fork: function (nextIndex) {
  3172. return new Context(this.source, nextIndex);
  3173. },
  3174. parse: function () {
  3175. var source = this.source;
  3176. var i = this.skip(IS_WHITESPACE, this.index);
  3177. var fork = this.fork(i);
  3178. var chr = at(source, i);
  3179. if (exec(IS_NUMBER_START, chr)) return fork.number();
  3180. switch (chr) {
  3181. case '{':
  3182. return fork.object();
  3183. case '[':
  3184. return fork.array();
  3185. case '"':
  3186. return fork.string();
  3187. case 't':
  3188. return fork.keyword(true);
  3189. case 'f':
  3190. return fork.keyword(false);
  3191. case 'n':
  3192. return fork.keyword(null);
  3193. } throw new SyntaxError('Unexpected character: "' + chr + '" at: ' + i);
  3194. },
  3195. node: function (type, value, start, end, nodes) {
  3196. return new Node(value, end, type ? null : slice(this.source, start, end), nodes);
  3197. },
  3198. object: function () {
  3199. var source = this.source;
  3200. var i = this.index + 1;
  3201. var expectKeypair = false;
  3202. var object = {};
  3203. var nodes = {};
  3204. while (i < source.length) {
  3205. i = this.until(['"', '}'], i);
  3206. if (at(source, i) === '}' && !expectKeypair) {
  3207. i++;
  3208. break;
  3209. }
  3210. // Parsing the key
  3211. var result = this.fork(i).string();
  3212. var key = result.value;
  3213. i = result.end;
  3214. i = this.until([':'], i) + 1;
  3215. // Parsing value
  3216. i = this.skip(IS_WHITESPACE, i);
  3217. result = this.fork(i).parse();
  3218. createProperty(nodes, key, result);
  3219. createProperty(object, key, result.value);
  3220. i = this.until([',', '}'], result.end);
  3221. var chr = at(source, i);
  3222. if (chr === ',') {
  3223. expectKeypair = true;
  3224. i++;
  3225. } else if (chr === '}') {
  3226. i++;
  3227. break;
  3228. }
  3229. }
  3230. return this.node(OBJECT, object, this.index, i, nodes);
  3231. },
  3232. array: function () {
  3233. var source = this.source;
  3234. var i = this.index + 1;
  3235. var expectElement = false;
  3236. var array = [];
  3237. var nodes = [];
  3238. while (i < source.length) {
  3239. i = this.skip(IS_WHITESPACE, i);
  3240. if (at(source, i) === ']' && !expectElement) {
  3241. i++;
  3242. break;
  3243. }
  3244. var result = this.fork(i).parse();
  3245. push(nodes, result);
  3246. push(array, result.value);
  3247. i = this.until([',', ']'], result.end);
  3248. if (at(source, i) === ',') {
  3249. expectElement = true;
  3250. i++;
  3251. } else if (at(source, i) === ']') {
  3252. i++;
  3253. break;
  3254. }
  3255. }
  3256. return this.node(OBJECT, array, this.index, i, nodes);
  3257. },
  3258. string: function () {
  3259. var index = this.index;
  3260. var parsed = parseJSONString(this.source, this.index + 1);
  3261. return this.node(PRIMITIVE, parsed.value, index, parsed.end);
  3262. },
  3263. number: function () {
  3264. var source = this.source;
  3265. var startIndex = this.index;
  3266. var i = startIndex;
  3267. if (at(source, i) === '-') i++;
  3268. if (at(source, i) === '0') i++;
  3269. else if (exec(IS_NON_ZERO_DIGIT, at(source, i))) i = this.skip(IS_DIGIT, i + 1);
  3270. else throw new SyntaxError('Failed to parse number at: ' + i);
  3271. if (at(source, i) === '.') i = this.skip(IS_DIGIT, i + 1);
  3272. if (at(source, i) === 'e' || at(source, i) === 'E') {
  3273. i++;
  3274. if (at(source, i) === '+' || at(source, i) === '-') i++;
  3275. var exponentStartIndex = i;
  3276. i = this.skip(IS_DIGIT, i);
  3277. if (exponentStartIndex === i) throw new SyntaxError("Failed to parse number's exponent value at: " + i);
  3278. }
  3279. return this.node(PRIMITIVE, Number(slice(source, startIndex, i)), startIndex, i);
  3280. },
  3281. keyword: function (value) {
  3282. var keyword = '' + value;
  3283. var index = this.index;
  3284. var endIndex = index + keyword.length;
  3285. if (slice(this.source, index, endIndex) !== keyword) throw new SyntaxError('Failed to parse value at: ' + index);
  3286. return this.node(PRIMITIVE, value, index, endIndex);
  3287. },
  3288. skip: function (regex, i) {
  3289. var source = this.source;
  3290. for (; i < source.length; i++) if (!exec(regex, at(source, i))) break;
  3291. return i;
  3292. },
  3293. until: function (array, i) {
  3294. i = this.skip(IS_WHITESPACE, i);
  3295. var chr = at(this.source, i);
  3296. for (var j = 0; j < array.length; j++) if (array[j] === chr) return i;
  3297. throw new SyntaxError('Unexpected character: "' + chr + '" at: ' + i);
  3298. }
  3299. };
  3300. var NO_SOURCE_SUPPORT = fails(function () {
  3301. var unsafeInt = '9007199254740993';
  3302. var source;
  3303. nativeParse(unsafeInt, function (key, value, context) {
  3304. source = context.source;
  3305. });
  3306. return source !== unsafeInt;
  3307. });
  3308. var PROPER_BASE_PARSE = NATIVE_SYMBOL && !fails(function () {
  3309. // Safari 9 bug
  3310. return 1 / nativeParse('-0 \t') !== -Infinity;
  3311. });
  3312. // `JSON.parse` method
  3313. // https://tc39.es/ecma262/#sec-json.parse
  3314. // https://github.com/tc39/proposal-json-parse-with-source
  3315. $({ target: 'JSON', stat: true, forced: NO_SOURCE_SUPPORT }, {
  3316. parse: function parse(text, reviver) {
  3317. return PROPER_BASE_PARSE && !isCallable(reviver) ? nativeParse(text) : $parse(text, reviver);
  3318. }
  3319. });
  3320. /***/ }),
  3321. /***/ 4979:
  3322. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  3323. var $ = __webpack_require__(6518);
  3324. var globalThis = __webpack_require__(4576);
  3325. var getBuiltIn = __webpack_require__(7751);
  3326. var createPropertyDescriptor = __webpack_require__(6980);
  3327. var defineProperty = (__webpack_require__(4913).f);
  3328. var hasOwn = __webpack_require__(9297);
  3329. var anInstance = __webpack_require__(679);
  3330. var inheritIfRequired = __webpack_require__(3167);
  3331. var normalizeStringArgument = __webpack_require__(2603);
  3332. var DOMExceptionConstants = __webpack_require__(5002);
  3333. var clearErrorStack = __webpack_require__(8574);
  3334. var DESCRIPTORS = __webpack_require__(3724);
  3335. var IS_PURE = __webpack_require__(6395);
  3336. var DOM_EXCEPTION = 'DOMException';
  3337. var Error = getBuiltIn('Error');
  3338. var NativeDOMException = getBuiltIn(DOM_EXCEPTION);
  3339. var $DOMException = function DOMException() {
  3340. anInstance(this, DOMExceptionPrototype);
  3341. var argumentsLength = arguments.length;
  3342. var message = normalizeStringArgument(argumentsLength < 1 ? undefined : arguments[0]);
  3343. var name = normalizeStringArgument(argumentsLength < 2 ? undefined : arguments[1], 'Error');
  3344. var that = new NativeDOMException(message, name);
  3345. var error = new Error(message);
  3346. error.name = DOM_EXCEPTION;
  3347. defineProperty(that, 'stack', createPropertyDescriptor(1, clearErrorStack(error.stack, 1)));
  3348. inheritIfRequired(that, this, $DOMException);
  3349. return that;
  3350. };
  3351. var DOMExceptionPrototype = $DOMException.prototype = NativeDOMException.prototype;
  3352. var ERROR_HAS_STACK = 'stack' in new Error(DOM_EXCEPTION);
  3353. var DOM_EXCEPTION_HAS_STACK = 'stack' in new NativeDOMException(1, 2);
  3354. // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
  3355. var descriptor = NativeDOMException && DESCRIPTORS && Object.getOwnPropertyDescriptor(globalThis, DOM_EXCEPTION);
  3356. // Bun ~ 0.1.1 DOMException have incorrect descriptor and we can't redefine it
  3357. // https://github.com/Jarred-Sumner/bun/issues/399
  3358. var BUGGY_DESCRIPTOR = !!descriptor && !(descriptor.writable && descriptor.configurable);
  3359. var FORCED_CONSTRUCTOR = ERROR_HAS_STACK && !BUGGY_DESCRIPTOR && !DOM_EXCEPTION_HAS_STACK;
  3360. // `DOMException` constructor patch for `.stack` where it's required
  3361. // https://webidl.spec.whatwg.org/#es-DOMException-specialness
  3362. $({ global: true, constructor: true, forced: IS_PURE || FORCED_CONSTRUCTOR }, { // TODO: fix export logic
  3363. DOMException: FORCED_CONSTRUCTOR ? $DOMException : NativeDOMException
  3364. });
  3365. var PolyfilledDOMException = getBuiltIn(DOM_EXCEPTION);
  3366. var PolyfilledDOMExceptionPrototype = PolyfilledDOMException.prototype;
  3367. if (PolyfilledDOMExceptionPrototype.constructor !== PolyfilledDOMException) {
  3368. if (!IS_PURE) {
  3369. defineProperty(PolyfilledDOMExceptionPrototype, 'constructor', createPropertyDescriptor(1, PolyfilledDOMException));
  3370. }
  3371. for (var key in DOMExceptionConstants) if (hasOwn(DOMExceptionConstants, key)) {
  3372. var constant = DOMExceptionConstants[key];
  3373. var constantName = constant.s;
  3374. if (!hasOwn(PolyfilledDOMException, constantName)) {
  3375. defineProperty(PolyfilledDOMException, constantName, createPropertyDescriptor(6, constant.c));
  3376. }
  3377. }
  3378. }
  3379. /***/ }),
  3380. /***/ 4603:
  3381. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  3382. var defineBuiltIn = __webpack_require__(6840);
  3383. var uncurryThis = __webpack_require__(9504);
  3384. var toString = __webpack_require__(655);
  3385. var validateArgumentsLength = __webpack_require__(2812);
  3386. var $URLSearchParams = URLSearchParams;
  3387. var URLSearchParamsPrototype = $URLSearchParams.prototype;
  3388. var append = uncurryThis(URLSearchParamsPrototype.append);
  3389. var $delete = uncurryThis(URLSearchParamsPrototype['delete']);
  3390. var forEach = uncurryThis(URLSearchParamsPrototype.forEach);
  3391. var push = uncurryThis([].push);
  3392. var params = new $URLSearchParams('a=1&a=2&b=3');
  3393. params['delete']('a', 1);
  3394. // `undefined` case is a Chromium 117 bug
  3395. // https://bugs.chromium.org/p/v8/issues/detail?id=14222
  3396. params['delete']('b', undefined);
  3397. if (params + '' !== 'a=2') {
  3398. defineBuiltIn(URLSearchParamsPrototype, 'delete', function (name /* , value */) {
  3399. var length = arguments.length;
  3400. var $value = length < 2 ? undefined : arguments[1];
  3401. if (length && $value === undefined) return $delete(this, name);
  3402. var entries = [];
  3403. forEach(this, function (v, k) { // also validates `this`
  3404. push(entries, { key: k, value: v });
  3405. });
  3406. validateArgumentsLength(length, 1);
  3407. var key = toString(name);
  3408. var value = toString($value);
  3409. var index = 0;
  3410. var dindex = 0;
  3411. var found = false;
  3412. var entriesLength = entries.length;
  3413. var entry;
  3414. while (index < entriesLength) {
  3415. entry = entries[index++];
  3416. if (found || entry.key === key) {
  3417. found = true;
  3418. $delete(this, entry.key);
  3419. } else dindex++;
  3420. }
  3421. while (dindex < entriesLength) {
  3422. entry = entries[dindex++];
  3423. if (!(entry.key === key && entry.value === value)) append(this, entry.key, entry.value);
  3424. }
  3425. }, { enumerable: true, unsafe: true });
  3426. }
  3427. /***/ }),
  3428. /***/ 7566:
  3429. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  3430. var defineBuiltIn = __webpack_require__(6840);
  3431. var uncurryThis = __webpack_require__(9504);
  3432. var toString = __webpack_require__(655);
  3433. var validateArgumentsLength = __webpack_require__(2812);
  3434. var $URLSearchParams = URLSearchParams;
  3435. var URLSearchParamsPrototype = $URLSearchParams.prototype;
  3436. var getAll = uncurryThis(URLSearchParamsPrototype.getAll);
  3437. var $has = uncurryThis(URLSearchParamsPrototype.has);
  3438. var params = new $URLSearchParams('a=1');
  3439. // `undefined` case is a Chromium 117 bug
  3440. // https://bugs.chromium.org/p/v8/issues/detail?id=14222
  3441. if (params.has('a', 2) || !params.has('a', undefined)) {
  3442. defineBuiltIn(URLSearchParamsPrototype, 'has', function has(name /* , value */) {
  3443. var length = arguments.length;
  3444. var $value = length < 2 ? undefined : arguments[1];
  3445. if (length && $value === undefined) return $has(this, name);
  3446. var values = getAll(this, name); // also validates `this`
  3447. validateArgumentsLength(length, 1);
  3448. var value = toString($value);
  3449. var index = 0;
  3450. while (index < values.length) {
  3451. if (values[index++] === value) return true;
  3452. } return false;
  3453. }, { enumerable: true, unsafe: true });
  3454. }
  3455. /***/ }),
  3456. /***/ 8721:
  3457. /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
  3458. var DESCRIPTORS = __webpack_require__(3724);
  3459. var uncurryThis = __webpack_require__(9504);
  3460. var defineBuiltInAccessor = __webpack_require__(2106);
  3461. var URLSearchParamsPrototype = URLSearchParams.prototype;
  3462. var forEach = uncurryThis(URLSearchParamsPrototype.forEach);
  3463. // `URLSearchParams.prototype.size` getter
  3464. // https://github.com/whatwg/url/pull/734
  3465. if (DESCRIPTORS && !('size' in URLSearchParamsPrototype)) {
  3466. defineBuiltInAccessor(URLSearchParamsPrototype, 'size', {
  3467. get: function size() {
  3468. var count = 0;
  3469. forEach(this, function () { count++; });
  3470. return count;
  3471. },
  3472. configurable: true,
  3473. enumerable: true
  3474. });
  3475. }
  3476. /***/ })
  3477. /******/ });
  3478. /************************************************************************/
  3479. /******/ // The module cache
  3480. /******/ var __webpack_module_cache__ = {};
  3481. /******/
  3482. /******/ // The require function
  3483. /******/ function __webpack_require__(moduleId) {
  3484. /******/ // Check if module is in cache
  3485. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  3486. /******/ if (cachedModule !== undefined) {
  3487. /******/ return cachedModule.exports;
  3488. /******/ }
  3489. /******/ // Create a new module (and put it into the cache)
  3490. /******/ var module = __webpack_module_cache__[moduleId] = {
  3491. /******/ // no module.id needed
  3492. /******/ // no module.loaded needed
  3493. /******/ exports: {}
  3494. /******/ };
  3495. /******/
  3496. /******/ // Execute the module function
  3497. /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  3498. /******/
  3499. /******/ // Return the exports of the module
  3500. /******/ return module.exports;
  3501. /******/ }
  3502. /******/
  3503. /************************************************************************/
  3504. /******/ /* webpack/runtime/define property getters */
  3505. /******/ (() => {
  3506. /******/ // define getter functions for harmony exports
  3507. /******/ __webpack_require__.d = (exports, definition) => {
  3508. /******/ for(var key in definition) {
  3509. /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  3510. /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
  3511. /******/ }
  3512. /******/ }
  3513. /******/ };
  3514. /******/ })();
  3515. /******/
  3516. /******/ /* webpack/runtime/hasOwnProperty shorthand */
  3517. /******/ (() => {
  3518. /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
  3519. /******/ })();
  3520. /******/
  3521. /************************************************************************/
  3522. var __webpack_exports__ = globalThis.pdfjsLib = {};
  3523. // EXPORTS
  3524. __webpack_require__.d(__webpack_exports__, {
  3525. AbortException: () => (/* reexport */ AbortException),
  3526. AnnotationEditorLayer: () => (/* reexport */ AnnotationEditorLayer),
  3527. AnnotationEditorParamsType: () => (/* reexport */ AnnotationEditorParamsType),
  3528. AnnotationEditorType: () => (/* reexport */ AnnotationEditorType),
  3529. AnnotationEditorUIManager: () => (/* reexport */ AnnotationEditorUIManager),
  3530. AnnotationLayer: () => (/* reexport */ AnnotationLayer),
  3531. AnnotationMode: () => (/* reexport */ AnnotationMode),
  3532. CMapCompressionType: () => (/* reexport */ CMapCompressionType),
  3533. ColorPicker: () => (/* reexport */ ColorPicker),
  3534. DOMSVGFactory: () => (/* reexport */ DOMSVGFactory),
  3535. DrawLayer: () => (/* reexport */ DrawLayer),
  3536. FeatureTest: () => (/* reexport */ util_FeatureTest),
  3537. GlobalWorkerOptions: () => (/* reexport */ GlobalWorkerOptions),
  3538. ImageKind: () => (/* reexport */ util_ImageKind),
  3539. InvalidPDFException: () => (/* reexport */ InvalidPDFException),
  3540. MissingPDFException: () => (/* reexport */ MissingPDFException),
  3541. OPS: () => (/* reexport */ OPS),
  3542. OutputScale: () => (/* reexport */ OutputScale),
  3543. PDFDataRangeTransport: () => (/* reexport */ PDFDataRangeTransport),
  3544. PDFDateString: () => (/* reexport */ PDFDateString),
  3545. PDFWorker: () => (/* reexport */ PDFWorker),
  3546. PasswordResponses: () => (/* reexport */ PasswordResponses),
  3547. PermissionFlag: () => (/* reexport */ PermissionFlag),
  3548. PixelsPerInch: () => (/* reexport */ PixelsPerInch),
  3549. RenderingCancelledException: () => (/* reexport */ RenderingCancelledException),
  3550. TextLayer: () => (/* reexport */ TextLayer),
  3551. UnexpectedResponseException: () => (/* reexport */ UnexpectedResponseException),
  3552. Util: () => (/* reexport */ Util),
  3553. VerbosityLevel: () => (/* reexport */ VerbosityLevel),
  3554. XfaLayer: () => (/* reexport */ XfaLayer),
  3555. build: () => (/* reexport */ build),
  3556. createValidAbsoluteUrl: () => (/* reexport */ createValidAbsoluteUrl),
  3557. fetchData: () => (/* reexport */ fetchData),
  3558. getDocument: () => (/* reexport */ getDocument),
  3559. getFilenameFromUrl: () => (/* reexport */ getFilenameFromUrl),
  3560. getPdfFilenameFromUrl: () => (/* reexport */ getPdfFilenameFromUrl),
  3561. getXfaPageViewport: () => (/* reexport */ getXfaPageViewport),
  3562. isDataScheme: () => (/* reexport */ isDataScheme),
  3563. isPdfFile: () => (/* reexport */ isPdfFile),
  3564. noContextMenu: () => (/* reexport */ noContextMenu),
  3565. normalizeUnicode: () => (/* reexport */ normalizeUnicode),
  3566. setLayerDimensions: () => (/* reexport */ setLayerDimensions),
  3567. shadow: () => (/* reexport */ shadow),
  3568. version: () => (/* reexport */ version)
  3569. });
  3570. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.array.push.js
  3571. var es_array_push = __webpack_require__(4114);
  3572. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.array-buffer.detached.js
  3573. var es_array_buffer_detached = __webpack_require__(6573);
  3574. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.array-buffer.transfer.js
  3575. var es_array_buffer_transfer = __webpack_require__(8100);
  3576. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.array-buffer.transfer-to-fixed-length.js
  3577. var es_array_buffer_transfer_to_fixed_length = __webpack_require__(7936);
  3578. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.typed-array.to-reversed.js
  3579. var es_typed_array_to_reversed = __webpack_require__(7467);
  3580. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.typed-array.to-sorted.js
  3581. var es_typed_array_to_sorted = __webpack_require__(4732);
  3582. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.typed-array.with.js
  3583. var es_typed_array_with = __webpack_require__(9577);
  3584. // EXTERNAL MODULE: ./node_modules/core-js/modules/web.url-search-params.delete.js
  3585. var web_url_search_params_delete = __webpack_require__(4603);
  3586. // EXTERNAL MODULE: ./node_modules/core-js/modules/web.url-search-params.has.js
  3587. var web_url_search_params_has = __webpack_require__(7566);
  3588. // EXTERNAL MODULE: ./node_modules/core-js/modules/web.url-search-params.size.js
  3589. var web_url_search_params_size = __webpack_require__(8721);
  3590. ;// ./src/shared/util.js
  3591. const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
  3592. const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  3593. const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  3594. const MAX_IMAGE_SIZE_TO_CACHE = 10e6;
  3595. const LINE_FACTOR = 1.35;
  3596. const LINE_DESCENT_FACTOR = 0.35;
  3597. const BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR;
  3598. const RenderingIntentFlag = {
  3599. ANY: 0x01,
  3600. DISPLAY: 0x02,
  3601. PRINT: 0x04,
  3602. SAVE: 0x08,
  3603. ANNOTATIONS_FORMS: 0x10,
  3604. ANNOTATIONS_STORAGE: 0x20,
  3605. ANNOTATIONS_DISABLE: 0x40,
  3606. IS_EDITING: 0x80,
  3607. OPLIST: 0x100
  3608. };
  3609. const AnnotationMode = {
  3610. DISABLE: 0,
  3611. ENABLE: 1,
  3612. ENABLE_FORMS: 2,
  3613. ENABLE_STORAGE: 3
  3614. };
  3615. const AnnotationEditorPrefix = "pdfjs_internal_editor_";
  3616. const AnnotationEditorType = {
  3617. DISABLE: -1,
  3618. NONE: 0,
  3619. FREETEXT: 3,
  3620. HIGHLIGHT: 9,
  3621. STAMP: 13,
  3622. INK: 15
  3623. };
  3624. const AnnotationEditorParamsType = {
  3625. RESIZE: 1,
  3626. CREATE: 2,
  3627. FREETEXT_SIZE: 11,
  3628. FREETEXT_COLOR: 12,
  3629. FREETEXT_OPACITY: 13,
  3630. INK_COLOR: 21,
  3631. INK_THICKNESS: 22,
  3632. INK_OPACITY: 23,
  3633. HIGHLIGHT_COLOR: 31,
  3634. HIGHLIGHT_DEFAULT_COLOR: 32,
  3635. HIGHLIGHT_THICKNESS: 33,
  3636. HIGHLIGHT_FREE: 34,
  3637. HIGHLIGHT_SHOW_ALL: 35
  3638. };
  3639. const PermissionFlag = {
  3640. PRINT: 0x04,
  3641. MODIFY_CONTENTS: 0x08,
  3642. COPY: 0x10,
  3643. MODIFY_ANNOTATIONS: 0x20,
  3644. FILL_INTERACTIVE_FORMS: 0x100,
  3645. COPY_FOR_ACCESSIBILITY: 0x200,
  3646. ASSEMBLE: 0x400,
  3647. PRINT_HIGH_QUALITY: 0x800
  3648. };
  3649. const TextRenderingMode = {
  3650. FILL: 0,
  3651. STROKE: 1,
  3652. FILL_STROKE: 2,
  3653. INVISIBLE: 3,
  3654. FILL_ADD_TO_PATH: 4,
  3655. STROKE_ADD_TO_PATH: 5,
  3656. FILL_STROKE_ADD_TO_PATH: 6,
  3657. ADD_TO_PATH: 7,
  3658. FILL_STROKE_MASK: 3,
  3659. ADD_TO_PATH_FLAG: 4
  3660. };
  3661. const util_ImageKind = {
  3662. GRAYSCALE_1BPP: 1,
  3663. RGB_24BPP: 2,
  3664. RGBA_32BPP: 3
  3665. };
  3666. const AnnotationType = {
  3667. TEXT: 1,
  3668. LINK: 2,
  3669. FREETEXT: 3,
  3670. LINE: 4,
  3671. SQUARE: 5,
  3672. CIRCLE: 6,
  3673. POLYGON: 7,
  3674. POLYLINE: 8,
  3675. HIGHLIGHT: 9,
  3676. UNDERLINE: 10,
  3677. SQUIGGLY: 11,
  3678. STRIKEOUT: 12,
  3679. STAMP: 13,
  3680. CARET: 14,
  3681. INK: 15,
  3682. POPUP: 16,
  3683. FILEATTACHMENT: 17,
  3684. SOUND: 18,
  3685. MOVIE: 19,
  3686. WIDGET: 20,
  3687. SCREEN: 21,
  3688. PRINTERMARK: 22,
  3689. TRAPNET: 23,
  3690. WATERMARK: 24,
  3691. THREED: 25,
  3692. REDACT: 26
  3693. };
  3694. const AnnotationReplyType = {
  3695. GROUP: "Group",
  3696. REPLY: "R"
  3697. };
  3698. const AnnotationFlag = {
  3699. INVISIBLE: 0x01,
  3700. HIDDEN: 0x02,
  3701. PRINT: 0x04,
  3702. NOZOOM: 0x08,
  3703. NOROTATE: 0x10,
  3704. NOVIEW: 0x20,
  3705. READONLY: 0x40,
  3706. LOCKED: 0x80,
  3707. TOGGLENOVIEW: 0x100,
  3708. LOCKEDCONTENTS: 0x200
  3709. };
  3710. const AnnotationFieldFlag = {
  3711. READONLY: 0x0000001,
  3712. REQUIRED: 0x0000002,
  3713. NOEXPORT: 0x0000004,
  3714. MULTILINE: 0x0001000,
  3715. PASSWORD: 0x0002000,
  3716. NOTOGGLETOOFF: 0x0004000,
  3717. RADIO: 0x0008000,
  3718. PUSHBUTTON: 0x0010000,
  3719. COMBO: 0x0020000,
  3720. EDIT: 0x0040000,
  3721. SORT: 0x0080000,
  3722. FILESELECT: 0x0100000,
  3723. MULTISELECT: 0x0200000,
  3724. DONOTSPELLCHECK: 0x0400000,
  3725. DONOTSCROLL: 0x0800000,
  3726. COMB: 0x1000000,
  3727. RICHTEXT: 0x2000000,
  3728. RADIOSINUNISON: 0x2000000,
  3729. COMMITONSELCHANGE: 0x4000000
  3730. };
  3731. const AnnotationBorderStyleType = {
  3732. SOLID: 1,
  3733. DASHED: 2,
  3734. BEVELED: 3,
  3735. INSET: 4,
  3736. UNDERLINE: 5
  3737. };
  3738. const AnnotationActionEventType = {
  3739. E: "Mouse Enter",
  3740. X: "Mouse Exit",
  3741. D: "Mouse Down",
  3742. U: "Mouse Up",
  3743. Fo: "Focus",
  3744. Bl: "Blur",
  3745. PO: "PageOpen",
  3746. PC: "PageClose",
  3747. PV: "PageVisible",
  3748. PI: "PageInvisible",
  3749. K: "Keystroke",
  3750. F: "Format",
  3751. V: "Validate",
  3752. C: "Calculate"
  3753. };
  3754. const DocumentActionEventType = {
  3755. WC: "WillClose",
  3756. WS: "WillSave",
  3757. DS: "DidSave",
  3758. WP: "WillPrint",
  3759. DP: "DidPrint"
  3760. };
  3761. const PageActionEventType = {
  3762. O: "PageOpen",
  3763. C: "PageClose"
  3764. };
  3765. const VerbosityLevel = {
  3766. ERRORS: 0,
  3767. WARNINGS: 1,
  3768. INFOS: 5
  3769. };
  3770. const CMapCompressionType = {
  3771. NONE: 0,
  3772. BINARY: 1
  3773. };
  3774. const OPS = {
  3775. dependency: 1,
  3776. setLineWidth: 2,
  3777. setLineCap: 3,
  3778. setLineJoin: 4,
  3779. setMiterLimit: 5,
  3780. setDash: 6,
  3781. setRenderingIntent: 7,
  3782. setFlatness: 8,
  3783. setGState: 9,
  3784. save: 10,
  3785. restore: 11,
  3786. transform: 12,
  3787. moveTo: 13,
  3788. lineTo: 14,
  3789. curveTo: 15,
  3790. curveTo2: 16,
  3791. curveTo3: 17,
  3792. closePath: 18,
  3793. rectangle: 19,
  3794. stroke: 20,
  3795. closeStroke: 21,
  3796. fill: 22,
  3797. eoFill: 23,
  3798. fillStroke: 24,
  3799. eoFillStroke: 25,
  3800. closeFillStroke: 26,
  3801. closeEOFillStroke: 27,
  3802. endPath: 28,
  3803. clip: 29,
  3804. eoClip: 30,
  3805. beginText: 31,
  3806. endText: 32,
  3807. setCharSpacing: 33,
  3808. setWordSpacing: 34,
  3809. setHScale: 35,
  3810. setLeading: 36,
  3811. setFont: 37,
  3812. setTextRenderingMode: 38,
  3813. setTextRise: 39,
  3814. moveText: 40,
  3815. setLeadingMoveText: 41,
  3816. setTextMatrix: 42,
  3817. nextLine: 43,
  3818. showText: 44,
  3819. showSpacedText: 45,
  3820. nextLineShowText: 46,
  3821. nextLineSetSpacingShowText: 47,
  3822. setCharWidth: 48,
  3823. setCharWidthAndBounds: 49,
  3824. setStrokeColorSpace: 50,
  3825. setFillColorSpace: 51,
  3826. setStrokeColor: 52,
  3827. setStrokeColorN: 53,
  3828. setFillColor: 54,
  3829. setFillColorN: 55,
  3830. setStrokeGray: 56,
  3831. setFillGray: 57,
  3832. setStrokeRGBColor: 58,
  3833. setFillRGBColor: 59,
  3834. setStrokeCMYKColor: 60,
  3835. setFillCMYKColor: 61,
  3836. shadingFill: 62,
  3837. beginInlineImage: 63,
  3838. beginImageData: 64,
  3839. endInlineImage: 65,
  3840. paintXObject: 66,
  3841. markPoint: 67,
  3842. markPointProps: 68,
  3843. beginMarkedContent: 69,
  3844. beginMarkedContentProps: 70,
  3845. endMarkedContent: 71,
  3846. beginCompat: 72,
  3847. endCompat: 73,
  3848. paintFormXObjectBegin: 74,
  3849. paintFormXObjectEnd: 75,
  3850. beginGroup: 76,
  3851. endGroup: 77,
  3852. beginAnnotation: 80,
  3853. endAnnotation: 81,
  3854. paintImageMaskXObject: 83,
  3855. paintImageMaskXObjectGroup: 84,
  3856. paintImageXObject: 85,
  3857. paintInlineImageXObject: 86,
  3858. paintInlineImageXObjectGroup: 87,
  3859. paintImageXObjectRepeat: 88,
  3860. paintImageMaskXObjectRepeat: 89,
  3861. paintSolidColorImageMask: 90,
  3862. constructPath: 91,
  3863. setStrokeTransparent: 92,
  3864. setFillTransparent: 93
  3865. };
  3866. const PasswordResponses = {
  3867. NEED_PASSWORD: 1,
  3868. INCORRECT_PASSWORD: 2
  3869. };
  3870. let verbosity = VerbosityLevel.WARNINGS;
  3871. function setVerbosityLevel(level) {
  3872. if (Number.isInteger(level)) {
  3873. verbosity = level;
  3874. }
  3875. }
  3876. function getVerbosityLevel() {
  3877. return verbosity;
  3878. }
  3879. function info(msg) {
  3880. if (verbosity >= VerbosityLevel.INFOS) {
  3881. console.log(`Info: ${msg}`);
  3882. }
  3883. }
  3884. function warn(msg) {
  3885. if (verbosity >= VerbosityLevel.WARNINGS) {
  3886. console.log(`Warning: ${msg}`);
  3887. }
  3888. }
  3889. function unreachable(msg) {
  3890. throw new Error(msg);
  3891. }
  3892. function assert(cond, msg) {
  3893. if (!cond) {
  3894. unreachable(msg);
  3895. }
  3896. }
  3897. function _isValidProtocol(url) {
  3898. switch (url?.protocol) {
  3899. case "http:":
  3900. case "https:":
  3901. case "ftp:":
  3902. case "mailto:":
  3903. case "tel:":
  3904. return true;
  3905. default:
  3906. return false;
  3907. }
  3908. }
  3909. function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
  3910. if (!url) {
  3911. return null;
  3912. }
  3913. try {
  3914. if (options && typeof url === "string") {
  3915. if (options.addDefaultProtocol && url.startsWith("www.")) {
  3916. const dots = url.match(/\./g);
  3917. if (dots?.length >= 2) {
  3918. url = `http://${url}`;
  3919. }
  3920. }
  3921. if (options.tryConvertEncoding) {
  3922. try {
  3923. url = stringToUTF8String(url);
  3924. } catch {}
  3925. }
  3926. }
  3927. const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
  3928. if (_isValidProtocol(absoluteUrl)) {
  3929. return absoluteUrl;
  3930. }
  3931. } catch {}
  3932. return null;
  3933. }
  3934. function shadow(obj, prop, value, nonSerializable = false) {
  3935. Object.defineProperty(obj, prop, {
  3936. value,
  3937. enumerable: !nonSerializable,
  3938. configurable: true,
  3939. writable: false
  3940. });
  3941. return value;
  3942. }
  3943. const BaseException = function BaseExceptionClosure() {
  3944. function BaseException(message, name) {
  3945. this.message = message;
  3946. this.name = name;
  3947. }
  3948. BaseException.prototype = new Error();
  3949. BaseException.constructor = BaseException;
  3950. return BaseException;
  3951. }();
  3952. class PasswordException extends BaseException {
  3953. constructor(msg, code) {
  3954. super(msg, "PasswordException");
  3955. this.code = code;
  3956. }
  3957. }
  3958. class UnknownErrorException extends BaseException {
  3959. constructor(msg, details) {
  3960. super(msg, "UnknownErrorException");
  3961. this.details = details;
  3962. }
  3963. }
  3964. class InvalidPDFException extends BaseException {
  3965. constructor(msg) {
  3966. super(msg, "InvalidPDFException");
  3967. }
  3968. }
  3969. class MissingPDFException extends BaseException {
  3970. constructor(msg) {
  3971. super(msg, "MissingPDFException");
  3972. }
  3973. }
  3974. class UnexpectedResponseException extends BaseException {
  3975. constructor(msg, status) {
  3976. super(msg, "UnexpectedResponseException");
  3977. this.status = status;
  3978. }
  3979. }
  3980. class FormatError extends BaseException {
  3981. constructor(msg) {
  3982. super(msg, "FormatError");
  3983. }
  3984. }
  3985. class AbortException extends BaseException {
  3986. constructor(msg) {
  3987. super(msg, "AbortException");
  3988. }
  3989. }
  3990. function bytesToString(bytes) {
  3991. if (typeof bytes !== "object" || bytes?.length === undefined) {
  3992. unreachable("Invalid argument for bytesToString");
  3993. }
  3994. const length = bytes.length;
  3995. const MAX_ARGUMENT_COUNT = 8192;
  3996. if (length < MAX_ARGUMENT_COUNT) {
  3997. return String.fromCharCode.apply(null, bytes);
  3998. }
  3999. const strBuf = [];
  4000. for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  4001. const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  4002. const chunk = bytes.subarray(i, chunkEnd);
  4003. strBuf.push(String.fromCharCode.apply(null, chunk));
  4004. }
  4005. return strBuf.join("");
  4006. }
  4007. function stringToBytes(str) {
  4008. if (typeof str !== "string") {
  4009. unreachable("Invalid argument for stringToBytes");
  4010. }
  4011. const length = str.length;
  4012. const bytes = new Uint8Array(length);
  4013. for (let i = 0; i < length; ++i) {
  4014. bytes[i] = str.charCodeAt(i) & 0xff;
  4015. }
  4016. return bytes;
  4017. }
  4018. function string32(value) {
  4019. return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
  4020. }
  4021. function objectSize(obj) {
  4022. return Object.keys(obj).length;
  4023. }
  4024. function objectFromMap(map) {
  4025. const obj = Object.create(null);
  4026. for (const [key, value] of map) {
  4027. obj[key] = value;
  4028. }
  4029. return obj;
  4030. }
  4031. function isLittleEndian() {
  4032. const buffer8 = new Uint8Array(4);
  4033. buffer8[0] = 1;
  4034. const view32 = new Uint32Array(buffer8.buffer, 0, 1);
  4035. return view32[0] === 1;
  4036. }
  4037. function isEvalSupported() {
  4038. try {
  4039. new Function("");
  4040. return true;
  4041. } catch {
  4042. return false;
  4043. }
  4044. }
  4045. class util_FeatureTest {
  4046. static get isLittleEndian() {
  4047. return shadow(this, "isLittleEndian", isLittleEndian());
  4048. }
  4049. static get isEvalSupported() {
  4050. return shadow(this, "isEvalSupported", isEvalSupported());
  4051. }
  4052. static get isOffscreenCanvasSupported() {
  4053. return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined");
  4054. }
  4055. static get platform() {
  4056. if (typeof navigator !== "undefined" && typeof navigator?.platform === "string") {
  4057. return shadow(this, "platform", {
  4058. isMac: navigator.platform.includes("Mac"),
  4059. isWindows: navigator.platform.includes("Win"),
  4060. isFirefox: typeof navigator?.userAgent === "string" && navigator.userAgent.includes("Firefox")
  4061. });
  4062. }
  4063. return shadow(this, "platform", {
  4064. isMac: false,
  4065. isWindows: false,
  4066. isFirefox: false
  4067. });
  4068. }
  4069. static get isCSSRoundSupported() {
  4070. return shadow(this, "isCSSRoundSupported", globalThis.CSS?.supports?.("width: round(1.5px, 1px)"));
  4071. }
  4072. }
  4073. const hexNumbers = Array.from(Array(256).keys(), n => n.toString(16).padStart(2, "0"));
  4074. class Util {
  4075. static makeHexColor(r, g, b) {
  4076. return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
  4077. }
  4078. static scaleMinMax(transform, minMax) {
  4079. let temp;
  4080. if (transform[0]) {
  4081. if (transform[0] < 0) {
  4082. temp = minMax[0];
  4083. minMax[0] = minMax[2];
  4084. minMax[2] = temp;
  4085. }
  4086. minMax[0] *= transform[0];
  4087. minMax[2] *= transform[0];
  4088. if (transform[3] < 0) {
  4089. temp = minMax[1];
  4090. minMax[1] = minMax[3];
  4091. minMax[3] = temp;
  4092. }
  4093. minMax[1] *= transform[3];
  4094. minMax[3] *= transform[3];
  4095. } else {
  4096. temp = minMax[0];
  4097. minMax[0] = minMax[1];
  4098. minMax[1] = temp;
  4099. temp = minMax[2];
  4100. minMax[2] = minMax[3];
  4101. minMax[3] = temp;
  4102. if (transform[1] < 0) {
  4103. temp = minMax[1];
  4104. minMax[1] = minMax[3];
  4105. minMax[3] = temp;
  4106. }
  4107. minMax[1] *= transform[1];
  4108. minMax[3] *= transform[1];
  4109. if (transform[2] < 0) {
  4110. temp = minMax[0];
  4111. minMax[0] = minMax[2];
  4112. minMax[2] = temp;
  4113. }
  4114. minMax[0] *= transform[2];
  4115. minMax[2] *= transform[2];
  4116. }
  4117. minMax[0] += transform[4];
  4118. minMax[1] += transform[5];
  4119. minMax[2] += transform[4];
  4120. minMax[3] += transform[5];
  4121. }
  4122. static transform(m1, m2) {
  4123. return [m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5]];
  4124. }
  4125. static applyTransform(p, m) {
  4126. const xt = p[0] * m[0] + p[1] * m[2] + m[4];
  4127. const yt = p[0] * m[1] + p[1] * m[3] + m[5];
  4128. return [xt, yt];
  4129. }
  4130. static applyInverseTransform(p, m) {
  4131. const d = m[0] * m[3] - m[1] * m[2];
  4132. const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  4133. const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  4134. return [xt, yt];
  4135. }
  4136. static getAxialAlignedBoundingBox(r, m) {
  4137. const p1 = this.applyTransform(r, m);
  4138. const p2 = this.applyTransform(r.slice(2, 4), m);
  4139. const p3 = this.applyTransform([r[0], r[3]], m);
  4140. const p4 = this.applyTransform([r[2], r[1]], m);
  4141. return [Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1])];
  4142. }
  4143. static inverseTransform(m) {
  4144. const d = m[0] * m[3] - m[1] * m[2];
  4145. return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
  4146. }
  4147. static singularValueDecompose2dScale(m) {
  4148. const transpose = [m[0], m[2], m[1], m[3]];
  4149. const a = m[0] * transpose[0] + m[1] * transpose[2];
  4150. const b = m[0] * transpose[1] + m[1] * transpose[3];
  4151. const c = m[2] * transpose[0] + m[3] * transpose[2];
  4152. const d = m[2] * transpose[1] + m[3] * transpose[3];
  4153. const first = (a + d) / 2;
  4154. const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
  4155. const sx = first + second || 1;
  4156. const sy = first - second || 1;
  4157. return [Math.sqrt(sx), Math.sqrt(sy)];
  4158. }
  4159. static normalizeRect(rect) {
  4160. const r = rect.slice(0);
  4161. if (rect[0] > rect[2]) {
  4162. r[0] = rect[2];
  4163. r[2] = rect[0];
  4164. }
  4165. if (rect[1] > rect[3]) {
  4166. r[1] = rect[3];
  4167. r[3] = rect[1];
  4168. }
  4169. return r;
  4170. }
  4171. static intersect(rect1, rect2) {
  4172. const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2]));
  4173. const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2]));
  4174. if (xLow > xHigh) {
  4175. return null;
  4176. }
  4177. const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3]));
  4178. const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3]));
  4179. if (yLow > yHigh) {
  4180. return null;
  4181. }
  4182. return [xLow, yLow, xHigh, yHigh];
  4183. }
  4184. static #getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, t, minMax) {
  4185. if (t <= 0 || t >= 1) {
  4186. return;
  4187. }
  4188. const mt = 1 - t;
  4189. const tt = t * t;
  4190. const ttt = tt * t;
  4191. const x = mt * (mt * (mt * x0 + 3 * t * x1) + 3 * tt * x2) + ttt * x3;
  4192. const y = mt * (mt * (mt * y0 + 3 * t * y1) + 3 * tt * y2) + ttt * y3;
  4193. minMax[0] = Math.min(minMax[0], x);
  4194. minMax[1] = Math.min(minMax[1], y);
  4195. minMax[2] = Math.max(minMax[2], x);
  4196. minMax[3] = Math.max(minMax[3], y);
  4197. }
  4198. static #getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, a, b, c, minMax) {
  4199. if (Math.abs(a) < 1e-12) {
  4200. if (Math.abs(b) >= 1e-12) {
  4201. this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, -c / b, minMax);
  4202. }
  4203. return;
  4204. }
  4205. const delta = b ** 2 - 4 * c * a;
  4206. if (delta < 0) {
  4207. return;
  4208. }
  4209. const sqrtDelta = Math.sqrt(delta);
  4210. const a2 = 2 * a;
  4211. this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b + sqrtDelta) / a2, minMax);
  4212. this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b - sqrtDelta) / a2, minMax);
  4213. }
  4214. static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
  4215. if (minMax) {
  4216. minMax[0] = Math.min(minMax[0], x0, x3);
  4217. minMax[1] = Math.min(minMax[1], y0, y3);
  4218. minMax[2] = Math.max(minMax[2], x0, x3);
  4219. minMax[3] = Math.max(minMax[3], y0, y3);
  4220. } else {
  4221. minMax = [Math.min(x0, x3), Math.min(y0, y3), Math.max(x0, x3), Math.max(y0, y3)];
  4222. }
  4223. this.#getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, 3 * (-x0 + 3 * (x1 - x2) + x3), 6 * (x0 - 2 * x1 + x2), 3 * (x1 - x0), minMax);
  4224. this.#getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, 3 * (-y0 + 3 * (y1 - y2) + y3), 6 * (y0 - 2 * y1 + y2), 3 * (y1 - y0), minMax);
  4225. return minMax;
  4226. }
  4227. }
  4228. const PDFStringTranslateTable = (/* unused pure expression or super */ null && ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2d8, 0x2c7, 0x2c6, 0x2d9, 0x2dd, 0x2db, 0x2da, 0x2dc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203a, 0x2212, 0x2030, 0x201e, 0x201c, 0x201d, 0x2018, 0x2019, 0x201a, 0x2122, 0xfb01, 0xfb02, 0x141, 0x152, 0x160, 0x178, 0x17d, 0x131, 0x142, 0x153, 0x161, 0x17e, 0, 0x20ac]));
  4229. function stringToPDFString(str) {
  4230. if (str[0] >= "\xEF") {
  4231. let encoding;
  4232. if (str[0] === "\xFE" && str[1] === "\xFF") {
  4233. encoding = "utf-16be";
  4234. if (str.length % 2 === 1) {
  4235. str = str.slice(0, -1);
  4236. }
  4237. } else if (str[0] === "\xFF" && str[1] === "\xFE") {
  4238. encoding = "utf-16le";
  4239. if (str.length % 2 === 1) {
  4240. str = str.slice(0, -1);
  4241. }
  4242. } else if (str[0] === "\xEF" && str[1] === "\xBB" && str[2] === "\xBF") {
  4243. encoding = "utf-8";
  4244. }
  4245. if (encoding) {
  4246. try {
  4247. const decoder = new TextDecoder(encoding, {
  4248. fatal: true
  4249. });
  4250. const buffer = stringToBytes(str);
  4251. const decoded = decoder.decode(buffer);
  4252. if (!decoded.includes("\x1b")) {
  4253. return decoded;
  4254. }
  4255. return decoded.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g, "");
  4256. } catch (ex) {
  4257. warn(`stringToPDFString: "${ex}".`);
  4258. }
  4259. }
  4260. }
  4261. const strBuf = [];
  4262. for (let i = 0, ii = str.length; i < ii; i++) {
  4263. const charCode = str.charCodeAt(i);
  4264. if (charCode === 0x1b) {
  4265. while (++i < ii && str.charCodeAt(i) !== 0x1b) {}
  4266. continue;
  4267. }
  4268. const code = PDFStringTranslateTable[charCode];
  4269. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  4270. }
  4271. return strBuf.join("");
  4272. }
  4273. function stringToUTF8String(str) {
  4274. return decodeURIComponent(escape(str));
  4275. }
  4276. function utf8StringToString(str) {
  4277. return unescape(encodeURIComponent(str));
  4278. }
  4279. function isArrayEqual(arr1, arr2) {
  4280. if (arr1.length !== arr2.length) {
  4281. return false;
  4282. }
  4283. for (let i = 0, ii = arr1.length; i < ii; i++) {
  4284. if (arr1[i] !== arr2[i]) {
  4285. return false;
  4286. }
  4287. }
  4288. return true;
  4289. }
  4290. function getModificationDate(date = new Date()) {
  4291. const buffer = [date.getUTCFullYear().toString(), (date.getUTCMonth() + 1).toString().padStart(2, "0"), date.getUTCDate().toString().padStart(2, "0"), date.getUTCHours().toString().padStart(2, "0"), date.getUTCMinutes().toString().padStart(2, "0"), date.getUTCSeconds().toString().padStart(2, "0")];
  4292. return buffer.join("");
  4293. }
  4294. let NormalizeRegex = null;
  4295. let NormalizationMap = null;
  4296. function normalizeUnicode(str) {
  4297. if (!NormalizeRegex) {
  4298. NormalizeRegex = /([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;
  4299. NormalizationMap = new Map([["ſt", "ſt"]]);
  4300. }
  4301. return str.replaceAll(NormalizeRegex, (_, p1, p2) => p1 ? p1.normalize("NFKC") : NormalizationMap.get(p2));
  4302. }
  4303. function getUuid() {
  4304. if (typeof crypto !== "undefined" && typeof crypto?.randomUUID === "function") {
  4305. return crypto.randomUUID();
  4306. }
  4307. const buf = new Uint8Array(32);
  4308. if (typeof crypto !== "undefined" && typeof crypto?.getRandomValues === "function") {
  4309. crypto.getRandomValues(buf);
  4310. } else {
  4311. for (let i = 0; i < 32; i++) {
  4312. buf[i] = Math.floor(Math.random() * 255);
  4313. }
  4314. }
  4315. return bytesToString(buf);
  4316. }
  4317. const AnnotationPrefix = "pdfjs_internal_id_";
  4318. const FontRenderOps = {
  4319. BEZIER_CURVE_TO: 0,
  4320. MOVE_TO: 1,
  4321. LINE_TO: 2,
  4322. QUADRATIC_CURVE_TO: 3,
  4323. RESTORE: 4,
  4324. SAVE: 5,
  4325. SCALE: 6,
  4326. TRANSFORM: 7,
  4327. TRANSLATE: 8
  4328. };
  4329. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.promise.with-resolvers.js
  4330. var es_promise_with_resolvers = __webpack_require__(4628);
  4331. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.difference.v2.js
  4332. var es_set_difference_v2 = __webpack_require__(7642);
  4333. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.intersection.v2.js
  4334. var es_set_intersection_v2 = __webpack_require__(8004);
  4335. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.is-disjoint-from.v2.js
  4336. var es_set_is_disjoint_from_v2 = __webpack_require__(3853);
  4337. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.is-subset-of.v2.js
  4338. var es_set_is_subset_of_v2 = __webpack_require__(5876);
  4339. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.is-superset-of.v2.js
  4340. var es_set_is_superset_of_v2 = __webpack_require__(2475);
  4341. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.symmetric-difference.v2.js
  4342. var es_set_symmetric_difference_v2 = __webpack_require__(5024);
  4343. // EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.union.v2.js
  4344. var es_set_union_v2 = __webpack_require__(1698);
  4345. // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.iterator.map.js
  4346. var esnext_iterator_map = __webpack_require__(1454);
  4347. // EXTERNAL MODULE: ./node_modules/core-js/modules/web.dom-exception.stack.js
  4348. var web_dom_exception_stack = __webpack_require__(4979);
  4349. // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.iterator.constructor.js
  4350. var esnext_iterator_constructor = __webpack_require__(8992);
  4351. // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.iterator.drop.js
  4352. var esnext_iterator_drop = __webpack_require__(4743);
  4353. // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.iterator.every.js
  4354. var esnext_iterator_every = __webpack_require__(3215);
  4355. // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.iterator.some.js
  4356. var esnext_iterator_some = __webpack_require__(7550);
  4357. // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.json.parse.js
  4358. var esnext_json_parse = __webpack_require__(8335);
  4359. // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.iterator.filter.js
  4360. var esnext_iterator_filter = __webpack_require__(4520);
  4361. ;// ./src/display/base_factory.js
  4362. class BaseFilterFactory {
  4363. addFilter(maps) {
  4364. return "none";
  4365. }
  4366. addHCMFilter(fgColor, bgColor) {
  4367. return "none";
  4368. }
  4369. addAlphaFilter(map) {
  4370. return "none";
  4371. }
  4372. addLuminosityFilter(map) {
  4373. return "none";
  4374. }
  4375. addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
  4376. return "none";
  4377. }
  4378. destroy(keepHCM = false) {}
  4379. }
  4380. class BaseCanvasFactory {
  4381. #enableHWA = false;
  4382. constructor({
  4383. enableHWA = false
  4384. }) {
  4385. this.#enableHWA = enableHWA;
  4386. }
  4387. create(width, height) {
  4388. if (width <= 0 || height <= 0) {
  4389. throw new Error("Invalid canvas size");
  4390. }
  4391. const canvas = this._createCanvas(width, height);
  4392. return {
  4393. canvas,
  4394. context: canvas.getContext("2d", {
  4395. willReadFrequently: !this.#enableHWA
  4396. })
  4397. };
  4398. }
  4399. reset(canvasAndContext, width, height) {
  4400. if (!canvasAndContext.canvas) {
  4401. throw new Error("Canvas is not specified");
  4402. }
  4403. if (width <= 0 || height <= 0) {
  4404. throw new Error("Invalid canvas size");
  4405. }
  4406. canvasAndContext.canvas.width = width;
  4407. canvasAndContext.canvas.height = height;
  4408. }
  4409. destroy(canvasAndContext) {
  4410. if (!canvasAndContext.canvas) {
  4411. throw new Error("Canvas is not specified");
  4412. }
  4413. canvasAndContext.canvas.width = 0;
  4414. canvasAndContext.canvas.height = 0;
  4415. canvasAndContext.canvas = null;
  4416. canvasAndContext.context = null;
  4417. }
  4418. _createCanvas(width, height) {
  4419. unreachable("Abstract method `_createCanvas` called.");
  4420. }
  4421. }
  4422. class BaseCMapReaderFactory {
  4423. constructor({
  4424. baseUrl = null,
  4425. isCompressed = true
  4426. }) {
  4427. this.baseUrl = baseUrl;
  4428. this.isCompressed = isCompressed;
  4429. }
  4430. async fetch({
  4431. name
  4432. }) {
  4433. if (!this.baseUrl) {
  4434. throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");
  4435. }
  4436. if (!name) {
  4437. throw new Error("CMap name must be specified.");
  4438. }
  4439. const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
  4440. const compressionType = this.isCompressed ? CMapCompressionType.BINARY : CMapCompressionType.NONE;
  4441. return this._fetchData(url, compressionType).catch(reason => {
  4442. throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
  4443. });
  4444. }
  4445. _fetchData(url, compressionType) {
  4446. unreachable("Abstract method `_fetchData` called.");
  4447. }
  4448. }
  4449. class BaseStandardFontDataFactory {
  4450. constructor({
  4451. baseUrl = null
  4452. }) {
  4453. this.baseUrl = baseUrl;
  4454. }
  4455. async fetch({
  4456. filename
  4457. }) {
  4458. if (!this.baseUrl) {
  4459. throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");
  4460. }
  4461. if (!filename) {
  4462. throw new Error("Font filename must be specified.");
  4463. }
  4464. const url = `${this.baseUrl}${filename}`;
  4465. return this._fetchData(url).catch(reason => {
  4466. throw new Error(`Unable to load font data at: ${url}`);
  4467. });
  4468. }
  4469. _fetchData(url) {
  4470. unreachable("Abstract method `_fetchData` called.");
  4471. }
  4472. }
  4473. class BaseSVGFactory {
  4474. create(width, height, skipDimensions = false) {
  4475. if (width <= 0 || height <= 0) {
  4476. throw new Error("Invalid SVG dimensions");
  4477. }
  4478. const svg = this._createSVG("svg:svg");
  4479. svg.setAttribute("version", "1.1");
  4480. if (!skipDimensions) {
  4481. svg.setAttribute("width", `${width}px`);
  4482. svg.setAttribute("height", `${height}px`);
  4483. }
  4484. svg.setAttribute("preserveAspectRatio", "none");
  4485. svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
  4486. return svg;
  4487. }
  4488. createElement(type) {
  4489. if (typeof type !== "string") {
  4490. throw new Error("Invalid SVG element type");
  4491. }
  4492. return this._createSVG(type);
  4493. }
  4494. _createSVG(type) {
  4495. unreachable("Abstract method `_createSVG` called.");
  4496. }
  4497. }
  4498. ;// ./src/display/display_utils.js
  4499. const SVG_NS = "http://www.w3.org/2000/svg";
  4500. class PixelsPerInch {
  4501. static CSS = 96.0;
  4502. static PDF = 72.0;
  4503. static PDF_TO_CSS_UNITS = this.CSS / this.PDF;
  4504. }
  4505. class DOMFilterFactory extends BaseFilterFactory {
  4506. #baseUrl;
  4507. #_cache;
  4508. #_defs;
  4509. #docId;
  4510. #document;
  4511. #_hcmCache;
  4512. #id = 0;
  4513. constructor({
  4514. docId,
  4515. ownerDocument = globalThis.document
  4516. }) {
  4517. super();
  4518. this.#docId = docId;
  4519. this.#document = ownerDocument;
  4520. }
  4521. get #cache() {
  4522. return this.#_cache ||= new Map();
  4523. }
  4524. get #hcmCache() {
  4525. return this.#_hcmCache ||= new Map();
  4526. }
  4527. get #defs() {
  4528. if (!this.#_defs) {
  4529. const div = this.#document.createElement("div");
  4530. const {
  4531. style
  4532. } = div;
  4533. style.visibility = "hidden";
  4534. style.contain = "strict";
  4535. style.width = style.height = 0;
  4536. style.position = "absolute";
  4537. style.top = style.left = 0;
  4538. style.zIndex = -1;
  4539. const svg = this.#document.createElementNS(SVG_NS, "svg");
  4540. svg.setAttribute("width", 0);
  4541. svg.setAttribute("height", 0);
  4542. this.#_defs = this.#document.createElementNS(SVG_NS, "defs");
  4543. div.append(svg);
  4544. svg.append(this.#_defs);
  4545. this.#document.body.append(div);
  4546. }
  4547. return this.#_defs;
  4548. }
  4549. #createTables(maps) {
  4550. if (maps.length === 1) {
  4551. const mapR = maps[0];
  4552. const buffer = new Array(256);
  4553. for (let i = 0; i < 256; i++) {
  4554. buffer[i] = mapR[i] / 255;
  4555. }
  4556. const table = buffer.join(",");
  4557. return [table, table, table];
  4558. }
  4559. const [mapR, mapG, mapB] = maps;
  4560. const bufferR = new Array(256);
  4561. const bufferG = new Array(256);
  4562. const bufferB = new Array(256);
  4563. for (let i = 0; i < 256; i++) {
  4564. bufferR[i] = mapR[i] / 255;
  4565. bufferG[i] = mapG[i] / 255;
  4566. bufferB[i] = mapB[i] / 255;
  4567. }
  4568. return [bufferR.join(","), bufferG.join(","), bufferB.join(",")];
  4569. }
  4570. #createUrl(id) {
  4571. if (this.#baseUrl === undefined) {
  4572. this.#baseUrl = "";
  4573. const url = this.#document.URL;
  4574. if (url !== this.#document.baseURI) {
  4575. if (isDataScheme(url)) {
  4576. warn('#createUrl: ignore "data:"-URL for performance reasons.');
  4577. } else {
  4578. this.#baseUrl = url.split("#", 1)[0];
  4579. }
  4580. }
  4581. }
  4582. return `url(${this.#baseUrl}#${id})`;
  4583. }
  4584. addFilter(maps) {
  4585. if (!maps) {
  4586. return "none";
  4587. }
  4588. let value = this.#cache.get(maps);
  4589. if (value) {
  4590. return value;
  4591. }
  4592. const [tableR, tableG, tableB] = this.#createTables(maps);
  4593. const key = maps.length === 1 ? tableR : `${tableR}${tableG}${tableB}`;
  4594. value = this.#cache.get(key);
  4595. if (value) {
  4596. this.#cache.set(maps, value);
  4597. return value;
  4598. }
  4599. const id = `g_${this.#docId}_transfer_map_${this.#id++}`;
  4600. const url = this.#createUrl(id);
  4601. this.#cache.set(maps, url);
  4602. this.#cache.set(key, url);
  4603. const filter = this.#createFilter(id);
  4604. this.#addTransferMapConversion(tableR, tableG, tableB, filter);
  4605. return url;
  4606. }
  4607. addHCMFilter(fgColor, bgColor) {
  4608. const key = `${fgColor}-${bgColor}`;
  4609. const filterName = "base";
  4610. let info = this.#hcmCache.get(filterName);
  4611. if (info?.key === key) {
  4612. return info.url;
  4613. }
  4614. if (info) {
  4615. info.filter?.remove();
  4616. info.key = key;
  4617. info.url = "none";
  4618. info.filter = null;
  4619. } else {
  4620. info = {
  4621. key,
  4622. url: "none",
  4623. filter: null
  4624. };
  4625. this.#hcmCache.set(filterName, info);
  4626. }
  4627. if (!fgColor || !bgColor) {
  4628. return info.url;
  4629. }
  4630. const fgRGB = this.#getRGB(fgColor);
  4631. fgColor = Util.makeHexColor(...fgRGB);
  4632. const bgRGB = this.#getRGB(bgColor);
  4633. bgColor = Util.makeHexColor(...bgRGB);
  4634. this.#defs.style.color = "";
  4635. if (fgColor === "#000000" && bgColor === "#ffffff" || fgColor === bgColor) {
  4636. return info.url;
  4637. }
  4638. const map = new Array(256);
  4639. for (let i = 0; i <= 255; i++) {
  4640. const x = i / 255;
  4641. map[i] = x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
  4642. }
  4643. const table = map.join(",");
  4644. const id = `g_${this.#docId}_hcm_filter`;
  4645. const filter = info.filter = this.#createFilter(id);
  4646. this.#addTransferMapConversion(table, table, table, filter);
  4647. this.#addGrayConversion(filter);
  4648. const getSteps = (c, n) => {
  4649. const start = fgRGB[c] / 255;
  4650. const end = bgRGB[c] / 255;
  4651. const arr = new Array(n + 1);
  4652. for (let i = 0; i <= n; i++) {
  4653. arr[i] = start + i / n * (end - start);
  4654. }
  4655. return arr.join(",");
  4656. };
  4657. this.#addTransferMapConversion(getSteps(0, 5), getSteps(1, 5), getSteps(2, 5), filter);
  4658. info.url = this.#createUrl(id);
  4659. return info.url;
  4660. }
  4661. addAlphaFilter(map) {
  4662. let value = this.#cache.get(map);
  4663. if (value) {
  4664. return value;
  4665. }
  4666. const [tableA] = this.#createTables([map]);
  4667. const key = `alpha_${tableA}`;
  4668. value = this.#cache.get(key);
  4669. if (value) {
  4670. this.#cache.set(map, value);
  4671. return value;
  4672. }
  4673. const id = `g_${this.#docId}_alpha_map_${this.#id++}`;
  4674. const url = this.#createUrl(id);
  4675. this.#cache.set(map, url);
  4676. this.#cache.set(key, url);
  4677. const filter = this.#createFilter(id);
  4678. this.#addTransferMapAlphaConversion(tableA, filter);
  4679. return url;
  4680. }
  4681. addLuminosityFilter(map) {
  4682. let value = this.#cache.get(map || "luminosity");
  4683. if (value) {
  4684. return value;
  4685. }
  4686. let tableA, key;
  4687. if (map) {
  4688. [tableA] = this.#createTables([map]);
  4689. key = `luminosity_${tableA}`;
  4690. } else {
  4691. key = "luminosity";
  4692. }
  4693. value = this.#cache.get(key);
  4694. if (value) {
  4695. this.#cache.set(map, value);
  4696. return value;
  4697. }
  4698. const id = `g_${this.#docId}_luminosity_map_${this.#id++}`;
  4699. const url = this.#createUrl(id);
  4700. this.#cache.set(map, url);
  4701. this.#cache.set(key, url);
  4702. const filter = this.#createFilter(id);
  4703. this.#addLuminosityConversion(filter);
  4704. if (map) {
  4705. this.#addTransferMapAlphaConversion(tableA, filter);
  4706. }
  4707. return url;
  4708. }
  4709. addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
  4710. const key = `${fgColor}-${bgColor}-${newFgColor}-${newBgColor}`;
  4711. let info = this.#hcmCache.get(filterName);
  4712. if (info?.key === key) {
  4713. return info.url;
  4714. }
  4715. if (info) {
  4716. info.filter?.remove();
  4717. info.key = key;
  4718. info.url = "none";
  4719. info.filter = null;
  4720. } else {
  4721. info = {
  4722. key,
  4723. url: "none",
  4724. filter: null
  4725. };
  4726. this.#hcmCache.set(filterName, info);
  4727. }
  4728. if (!fgColor || !bgColor) {
  4729. return info.url;
  4730. }
  4731. const [fgRGB, bgRGB] = [fgColor, bgColor].map(this.#getRGB.bind(this));
  4732. let fgGray = Math.round(0.2126 * fgRGB[0] + 0.7152 * fgRGB[1] + 0.0722 * fgRGB[2]);
  4733. let bgGray = Math.round(0.2126 * bgRGB[0] + 0.7152 * bgRGB[1] + 0.0722 * bgRGB[2]);
  4734. let [newFgRGB, newBgRGB] = [newFgColor, newBgColor].map(this.#getRGB.bind(this));
  4735. if (bgGray < fgGray) {
  4736. [fgGray, bgGray, newFgRGB, newBgRGB] = [bgGray, fgGray, newBgRGB, newFgRGB];
  4737. }
  4738. this.#defs.style.color = "";
  4739. const getSteps = (fg, bg, n) => {
  4740. const arr = new Array(256);
  4741. const step = (bgGray - fgGray) / n;
  4742. const newStart = fg / 255;
  4743. const newStep = (bg - fg) / (255 * n);
  4744. let prev = 0;
  4745. for (let i = 0; i <= n; i++) {
  4746. const k = Math.round(fgGray + i * step);
  4747. const value = newStart + i * newStep;
  4748. for (let j = prev; j <= k; j++) {
  4749. arr[j] = value;
  4750. }
  4751. prev = k + 1;
  4752. }
  4753. for (let i = prev; i < 256; i++) {
  4754. arr[i] = arr[prev - 1];
  4755. }
  4756. return arr.join(",");
  4757. };
  4758. const id = `g_${this.#docId}_hcm_${filterName}_filter`;
  4759. const filter = info.filter = this.#createFilter(id);
  4760. this.#addGrayConversion(filter);
  4761. this.#addTransferMapConversion(getSteps(newFgRGB[0], newBgRGB[0], 5), getSteps(newFgRGB[1], newBgRGB[1], 5), getSteps(newFgRGB[2], newBgRGB[2], 5), filter);
  4762. info.url = this.#createUrl(id);
  4763. return info.url;
  4764. }
  4765. destroy(keepHCM = false) {
  4766. if (keepHCM && this.#hcmCache.size !== 0) {
  4767. return;
  4768. }
  4769. if (this.#_defs) {
  4770. this.#_defs.parentNode.parentNode.remove();
  4771. this.#_defs = null;
  4772. }
  4773. if (this.#_cache) {
  4774. this.#_cache.clear();
  4775. this.#_cache = null;
  4776. }
  4777. this.#id = 0;
  4778. }
  4779. #addLuminosityConversion(filter) {
  4780. const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix");
  4781. feColorMatrix.setAttribute("type", "matrix");
  4782. feColorMatrix.setAttribute("values", "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0");
  4783. filter.append(feColorMatrix);
  4784. }
  4785. #addGrayConversion(filter) {
  4786. const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix");
  4787. feColorMatrix.setAttribute("type", "matrix");
  4788. feColorMatrix.setAttribute("values", "0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0");
  4789. filter.append(feColorMatrix);
  4790. }
  4791. #createFilter(id) {
  4792. const filter = this.#document.createElementNS(SVG_NS, "filter");
  4793. filter.setAttribute("color-interpolation-filters", "sRGB");
  4794. filter.setAttribute("id", id);
  4795. this.#defs.append(filter);
  4796. return filter;
  4797. }
  4798. #appendFeFunc(feComponentTransfer, func, table) {
  4799. const feFunc = this.#document.createElementNS(SVG_NS, func);
  4800. feFunc.setAttribute("type", "discrete");
  4801. feFunc.setAttribute("tableValues", table);
  4802. feComponentTransfer.append(feFunc);
  4803. }
  4804. #addTransferMapConversion(rTable, gTable, bTable, filter) {
  4805. const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer");
  4806. filter.append(feComponentTransfer);
  4807. this.#appendFeFunc(feComponentTransfer, "feFuncR", rTable);
  4808. this.#appendFeFunc(feComponentTransfer, "feFuncG", gTable);
  4809. this.#appendFeFunc(feComponentTransfer, "feFuncB", bTable);
  4810. }
  4811. #addTransferMapAlphaConversion(aTable, filter) {
  4812. const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer");
  4813. filter.append(feComponentTransfer);
  4814. this.#appendFeFunc(feComponentTransfer, "feFuncA", aTable);
  4815. }
  4816. #getRGB(color) {
  4817. this.#defs.style.color = color;
  4818. return getRGB(getComputedStyle(this.#defs).getPropertyValue("color"));
  4819. }
  4820. }
  4821. class DOMCanvasFactory extends BaseCanvasFactory {
  4822. constructor({
  4823. ownerDocument = globalThis.document,
  4824. enableHWA = false
  4825. }) {
  4826. super({
  4827. enableHWA
  4828. });
  4829. this._document = ownerDocument;
  4830. }
  4831. _createCanvas(width, height) {
  4832. const canvas = this._document.createElement("canvas");
  4833. canvas.width = width;
  4834. canvas.height = height;
  4835. return canvas;
  4836. }
  4837. }
  4838. async function fetchData(url, type = "text") {
  4839. if (isValidFetchUrl(url, document.baseURI)) {
  4840. const response = await fetch(url);
  4841. if (!response.ok) {
  4842. throw new Error(response.statusText);
  4843. }
  4844. switch (type) {
  4845. case "arraybuffer":
  4846. return response.arrayBuffer();
  4847. case "blob":
  4848. return response.blob();
  4849. case "json":
  4850. return response.json();
  4851. }
  4852. return response.text();
  4853. }
  4854. return new Promise((resolve, reject) => {
  4855. const request = new XMLHttpRequest();
  4856. request.open("GET", url, true);
  4857. request.responseType = type;
  4858. request.onreadystatechange = () => {
  4859. if (request.readyState !== XMLHttpRequest.DONE) {
  4860. return;
  4861. }
  4862. if (request.status === 200 || request.status === 0) {
  4863. switch (type) {
  4864. case "arraybuffer":
  4865. case "blob":
  4866. case "json":
  4867. resolve(request.response);
  4868. return;
  4869. }
  4870. resolve(request.responseText);
  4871. return;
  4872. }
  4873. reject(new Error(request.statusText));
  4874. };
  4875. request.send(null);
  4876. });
  4877. }
  4878. class DOMCMapReaderFactory extends BaseCMapReaderFactory {
  4879. _fetchData(url, compressionType) {
  4880. return fetchData(url, this.isCompressed ? "arraybuffer" : "text").then(data => ({
  4881. cMapData: data instanceof ArrayBuffer ? new Uint8Array(data) : stringToBytes(data),
  4882. compressionType
  4883. }));
  4884. }
  4885. }
  4886. class DOMStandardFontDataFactory extends BaseStandardFontDataFactory {
  4887. _fetchData(url) {
  4888. return fetchData(url, "arraybuffer").then(data => new Uint8Array(data));
  4889. }
  4890. }
  4891. class DOMSVGFactory extends BaseSVGFactory {
  4892. _createSVG(type) {
  4893. return document.createElementNS(SVG_NS, type);
  4894. }
  4895. }
  4896. class PageViewport {
  4897. constructor({
  4898. viewBox,
  4899. scale,
  4900. rotation,
  4901. offsetX = 0,
  4902. offsetY = 0,
  4903. dontFlip = false
  4904. }) {
  4905. this.viewBox = viewBox;
  4906. this.scale = scale;
  4907. this.rotation = rotation;
  4908. this.offsetX = offsetX;
  4909. this.offsetY = offsetY;
  4910. const centerX = (viewBox[2] + viewBox[0]) / 2;
  4911. const centerY = (viewBox[3] + viewBox[1]) / 2;
  4912. let rotateA, rotateB, rotateC, rotateD;
  4913. rotation %= 360;
  4914. if (rotation < 0) {
  4915. rotation += 360;
  4916. }
  4917. switch (rotation) {
  4918. case 180:
  4919. rotateA = -1;
  4920. rotateB = 0;
  4921. rotateC = 0;
  4922. rotateD = 1;
  4923. break;
  4924. case 90:
  4925. rotateA = 0;
  4926. rotateB = 1;
  4927. rotateC = 1;
  4928. rotateD = 0;
  4929. break;
  4930. case 270:
  4931. rotateA = 0;
  4932. rotateB = -1;
  4933. rotateC = -1;
  4934. rotateD = 0;
  4935. break;
  4936. case 0:
  4937. rotateA = 1;
  4938. rotateB = 0;
  4939. rotateC = 0;
  4940. rotateD = -1;
  4941. break;
  4942. default:
  4943. throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
  4944. }
  4945. if (dontFlip) {
  4946. rotateC = -rotateC;
  4947. rotateD = -rotateD;
  4948. }
  4949. let offsetCanvasX, offsetCanvasY;
  4950. let width, height;
  4951. if (rotateA === 0) {
  4952. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  4953. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  4954. width = (viewBox[3] - viewBox[1]) * scale;
  4955. height = (viewBox[2] - viewBox[0]) * scale;
  4956. } else {
  4957. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  4958. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  4959. width = (viewBox[2] - viewBox[0]) * scale;
  4960. height = (viewBox[3] - viewBox[1]) * scale;
  4961. }
  4962. this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
  4963. this.width = width;
  4964. this.height = height;
  4965. }
  4966. get rawDims() {
  4967. const {
  4968. viewBox
  4969. } = this;
  4970. return shadow(this, "rawDims", {
  4971. pageWidth: viewBox[2] - viewBox[0],
  4972. pageHeight: viewBox[3] - viewBox[1],
  4973. pageX: viewBox[0],
  4974. pageY: viewBox[1]
  4975. });
  4976. }
  4977. clone({
  4978. scale = this.scale,
  4979. rotation = this.rotation,
  4980. offsetX = this.offsetX,
  4981. offsetY = this.offsetY,
  4982. dontFlip = false
  4983. } = {}) {
  4984. return new PageViewport({
  4985. viewBox: this.viewBox.slice(),
  4986. scale,
  4987. rotation,
  4988. offsetX,
  4989. offsetY,
  4990. dontFlip
  4991. });
  4992. }
  4993. convertToViewportPoint(x, y) {
  4994. return Util.applyTransform([x, y], this.transform);
  4995. }
  4996. convertToViewportRectangle(rect) {
  4997. const topLeft = Util.applyTransform([rect[0], rect[1]], this.transform);
  4998. const bottomRight = Util.applyTransform([rect[2], rect[3]], this.transform);
  4999. return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
  5000. }
  5001. convertToPdfPoint(x, y) {
  5002. return Util.applyInverseTransform([x, y], this.transform);
  5003. }
  5004. }
  5005. class RenderingCancelledException extends BaseException {
  5006. constructor(msg, extraDelay = 0) {
  5007. super(msg, "RenderingCancelledException");
  5008. this.extraDelay = extraDelay;
  5009. }
  5010. }
  5011. function isDataScheme(url) {
  5012. const ii = url.length;
  5013. let i = 0;
  5014. while (i < ii && url[i].trim() === "") {
  5015. i++;
  5016. }
  5017. return url.substring(i, i + 5).toLowerCase() === "data:";
  5018. }
  5019. function isPdfFile(filename) {
  5020. return typeof filename === "string" && /\.pdf$/i.test(filename);
  5021. }
  5022. function getFilenameFromUrl(url) {
  5023. [url] = url.split(/[#?]/, 1);
  5024. return url.substring(url.lastIndexOf("/") + 1);
  5025. }
  5026. function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
  5027. if (typeof url !== "string") {
  5028. return defaultFilename;
  5029. }
  5030. if (isDataScheme(url)) {
  5031. warn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
  5032. return defaultFilename;
  5033. }
  5034. const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  5035. const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  5036. const splitURI = reURI.exec(url);
  5037. let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
  5038. if (suggestedFilename) {
  5039. suggestedFilename = suggestedFilename[0];
  5040. if (suggestedFilename.includes("%")) {
  5041. try {
  5042. suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  5043. } catch {}
  5044. }
  5045. }
  5046. return suggestedFilename || defaultFilename;
  5047. }
  5048. class StatTimer {
  5049. started = Object.create(null);
  5050. times = [];
  5051. time(name) {
  5052. if (name in this.started) {
  5053. warn(`Timer is already running for ${name}`);
  5054. }
  5055. this.started[name] = Date.now();
  5056. }
  5057. timeEnd(name) {
  5058. if (!(name in this.started)) {
  5059. warn(`Timer has not been started for ${name}`);
  5060. }
  5061. this.times.push({
  5062. name,
  5063. start: this.started[name],
  5064. end: Date.now()
  5065. });
  5066. delete this.started[name];
  5067. }
  5068. toString() {
  5069. const outBuf = [];
  5070. let longest = 0;
  5071. for (const {
  5072. name
  5073. } of this.times) {
  5074. longest = Math.max(name.length, longest);
  5075. }
  5076. for (const {
  5077. name,
  5078. start,
  5079. end
  5080. } of this.times) {
  5081. outBuf.push(`${name.padEnd(longest)} ${end - start}ms\n`);
  5082. }
  5083. return outBuf.join("");
  5084. }
  5085. }
  5086. function isValidFetchUrl(url, baseUrl) {
  5087. try {
  5088. const {
  5089. protocol
  5090. } = baseUrl ? new URL(url, baseUrl) : new URL(url);
  5091. return protocol === "http:" || protocol === "https:";
  5092. } catch {
  5093. return false;
  5094. }
  5095. }
  5096. function noContextMenu(e) {
  5097. e.preventDefault();
  5098. }
  5099. function deprecated(details) {
  5100. console.log("Deprecated API usage: " + details);
  5101. }
  5102. let pdfDateStringRegex;
  5103. class PDFDateString {
  5104. static toDateObject(input) {
  5105. if (!input || typeof input !== "string") {
  5106. return null;
  5107. }
  5108. pdfDateStringRegex ||= new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
  5109. const matches = pdfDateStringRegex.exec(input);
  5110. if (!matches) {
  5111. return null;
  5112. }
  5113. const year = parseInt(matches[1], 10);
  5114. let month = parseInt(matches[2], 10);
  5115. month = month >= 1 && month <= 12 ? month - 1 : 0;
  5116. let day = parseInt(matches[3], 10);
  5117. day = day >= 1 && day <= 31 ? day : 1;
  5118. let hour = parseInt(matches[4], 10);
  5119. hour = hour >= 0 && hour <= 23 ? hour : 0;
  5120. let minute = parseInt(matches[5], 10);
  5121. minute = minute >= 0 && minute <= 59 ? minute : 0;
  5122. let second = parseInt(matches[6], 10);
  5123. second = second >= 0 && second <= 59 ? second : 0;
  5124. const universalTimeRelation = matches[7] || "Z";
  5125. let offsetHour = parseInt(matches[8], 10);
  5126. offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
  5127. let offsetMinute = parseInt(matches[9], 10) || 0;
  5128. offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
  5129. if (universalTimeRelation === "-") {
  5130. hour += offsetHour;
  5131. minute += offsetMinute;
  5132. } else if (universalTimeRelation === "+") {
  5133. hour -= offsetHour;
  5134. minute -= offsetMinute;
  5135. }
  5136. return new Date(Date.UTC(year, month, day, hour, minute, second));
  5137. }
  5138. }
  5139. function getXfaPageViewport(xfaPage, {
  5140. scale = 1,
  5141. rotation = 0
  5142. }) {
  5143. const {
  5144. width,
  5145. height
  5146. } = xfaPage.attributes.style;
  5147. const viewBox = [0, 0, parseInt(width), parseInt(height)];
  5148. return new PageViewport({
  5149. viewBox,
  5150. scale,
  5151. rotation
  5152. });
  5153. }
  5154. function getRGB(color) {
  5155. if (color.startsWith("#")) {
  5156. const colorRGB = parseInt(color.slice(1), 16);
  5157. return [(colorRGB & 0xff0000) >> 16, (colorRGB & 0x00ff00) >> 8, colorRGB & 0x0000ff];
  5158. }
  5159. if (color.startsWith("rgb(")) {
  5160. return color.slice(4, -1).split(",").map(x => parseInt(x));
  5161. }
  5162. if (color.startsWith("rgba(")) {
  5163. return color.slice(5, -1).split(",").map(x => parseInt(x)).slice(0, 3);
  5164. }
  5165. warn(`Not a valid color format: "${color}"`);
  5166. return [0, 0, 0];
  5167. }
  5168. function getColorValues(colors) {
  5169. const span = document.createElement("span");
  5170. span.style.visibility = "hidden";
  5171. document.body.append(span);
  5172. for (const name of colors.keys()) {
  5173. span.style.color = name;
  5174. const computedColor = window.getComputedStyle(span).color;
  5175. colors.set(name, getRGB(computedColor));
  5176. }
  5177. span.remove();
  5178. }
  5179. function getCurrentTransform(ctx) {
  5180. const {
  5181. a,
  5182. b,
  5183. c,
  5184. d,
  5185. e,
  5186. f
  5187. } = ctx.getTransform();
  5188. return [a, b, c, d, e, f];
  5189. }
  5190. function getCurrentTransformInverse(ctx) {
  5191. const {
  5192. a,
  5193. b,
  5194. c,
  5195. d,
  5196. e,
  5197. f
  5198. } = ctx.getTransform().invertSelf();
  5199. return [a, b, c, d, e, f];
  5200. }
  5201. function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) {
  5202. if (viewport instanceof PageViewport) {
  5203. const {
  5204. pageWidth,
  5205. pageHeight
  5206. } = viewport.rawDims;
  5207. const {
  5208. style
  5209. } = div;
  5210. const useRound = util_FeatureTest.isCSSRoundSupported;
  5211. const w = `var(--scale-factor) * ${pageWidth}px`,
  5212. h = `var(--scale-factor) * ${pageHeight}px`;
  5213. const widthStr = useRound ? `round(down, ${w}, var(--scale-round-x, 1px))` : `calc(${w})`,
  5214. heightStr = useRound ? `round(down, ${h}, var(--scale-round-y, 1px))` : `calc(${h})`;
  5215. if (!mustFlip || viewport.rotation % 180 === 0) {
  5216. style.width = widthStr;
  5217. style.height = heightStr;
  5218. } else {
  5219. style.width = heightStr;
  5220. style.height = widthStr;
  5221. }
  5222. }
  5223. if (mustRotate) {
  5224. div.setAttribute("data-main-rotation", viewport.rotation);
  5225. }
  5226. }
  5227. class OutputScale {
  5228. constructor() {
  5229. const pixelRatio = window.devicePixelRatio || 1;
  5230. this.sx = pixelRatio;
  5231. this.sy = pixelRatio;
  5232. }
  5233. get scaled() {
  5234. return this.sx !== 1 || this.sy !== 1;
  5235. }
  5236. get symmetric() {
  5237. return this.sx === this.sy;
  5238. }
  5239. }
  5240. ;// ./src/display/editor/toolbar.js
  5241. class EditorToolbar {
  5242. #toolbar = null;
  5243. #colorPicker = null;
  5244. #editor;
  5245. #buttons = null;
  5246. #altText = null;
  5247. static #l10nRemove = null;
  5248. constructor(editor) {
  5249. this.#editor = editor;
  5250. EditorToolbar.#l10nRemove ||= Object.freeze({
  5251. freetext: "pdfjs-editor-remove-freetext-button",
  5252. highlight: "pdfjs-editor-remove-highlight-button",
  5253. ink: "pdfjs-editor-remove-ink-button",
  5254. stamp: "pdfjs-editor-remove-stamp-button"
  5255. });
  5256. }
  5257. render() {
  5258. const editToolbar = this.#toolbar = document.createElement("div");
  5259. editToolbar.classList.add("editToolbar", "hidden");
  5260. editToolbar.setAttribute("role", "toolbar");
  5261. const signal = this.#editor._uiManager._signal;
  5262. editToolbar.addEventListener("contextmenu", noContextMenu, {
  5263. signal
  5264. });
  5265. editToolbar.addEventListener("pointerdown", EditorToolbar.#pointerDown, {
  5266. signal
  5267. });
  5268. const buttons = this.#buttons = document.createElement("div");
  5269. buttons.className = "buttons";
  5270. editToolbar.append(buttons);
  5271. const position = this.#editor.toolbarPosition;
  5272. if (position) {
  5273. const {
  5274. style
  5275. } = editToolbar;
  5276. const x = this.#editor._uiManager.direction === "ltr" ? 1 - position[0] : position[0];
  5277. style.insetInlineEnd = `${100 * x}%`;
  5278. style.top = `calc(${100 * position[1]}% + var(--editor-toolbar-vert-offset))`;
  5279. }
  5280. this.#addDeleteButton();
  5281. return editToolbar;
  5282. }
  5283. get div() {
  5284. return this.#toolbar;
  5285. }
  5286. static #pointerDown(e) {
  5287. e.stopPropagation();
  5288. }
  5289. #focusIn(e) {
  5290. this.#editor._focusEventsAllowed = false;
  5291. e.preventDefault();
  5292. e.stopPropagation();
  5293. }
  5294. #focusOut(e) {
  5295. this.#editor._focusEventsAllowed = true;
  5296. e.preventDefault();
  5297. e.stopPropagation();
  5298. }
  5299. #addListenersToElement(element) {
  5300. const signal = this.#editor._uiManager._signal;
  5301. element.addEventListener("focusin", this.#focusIn.bind(this), {
  5302. capture: true,
  5303. signal
  5304. });
  5305. element.addEventListener("focusout", this.#focusOut.bind(this), {
  5306. capture: true,
  5307. signal
  5308. });
  5309. element.addEventListener("contextmenu", noContextMenu, {
  5310. signal
  5311. });
  5312. }
  5313. hide() {
  5314. this.#toolbar.classList.add("hidden");
  5315. this.#colorPicker?.hideDropdown();
  5316. }
  5317. show() {
  5318. this.#toolbar.classList.remove("hidden");
  5319. this.#altText?.shown();
  5320. }
  5321. #addDeleteButton() {
  5322. const {
  5323. editorType,
  5324. _uiManager
  5325. } = this.#editor;
  5326. const button = document.createElement("button");
  5327. button.className = "delete";
  5328. button.tabIndex = 0;
  5329. button.setAttribute("data-l10n-id", EditorToolbar.#l10nRemove[editorType]);
  5330. this.#addListenersToElement(button);
  5331. button.addEventListener("click", e => {
  5332. _uiManager.delete();
  5333. }, {
  5334. signal: _uiManager._signal
  5335. });
  5336. this.#buttons.append(button);
  5337. }
  5338. get #divider() {
  5339. const divider = document.createElement("div");
  5340. divider.className = "divider";
  5341. return divider;
  5342. }
  5343. async addAltText(altText) {
  5344. const button = await altText.render();
  5345. this.#addListenersToElement(button);
  5346. this.#buttons.prepend(button, this.#divider);
  5347. this.#altText = altText;
  5348. }
  5349. addColorPicker(colorPicker) {
  5350. this.#colorPicker = colorPicker;
  5351. const button = colorPicker.renderButton();
  5352. this.#addListenersToElement(button);
  5353. this.#buttons.prepend(button, this.#divider);
  5354. }
  5355. remove() {
  5356. this.#toolbar.remove();
  5357. this.#colorPicker?.destroy();
  5358. this.#colorPicker = null;
  5359. }
  5360. }
  5361. class HighlightToolbar {
  5362. #buttons = null;
  5363. #toolbar = null;
  5364. #uiManager;
  5365. constructor(uiManager) {
  5366. this.#uiManager = uiManager;
  5367. }
  5368. #render() {
  5369. const editToolbar = this.#toolbar = document.createElement("div");
  5370. editToolbar.className = "editToolbar";
  5371. editToolbar.setAttribute("role", "toolbar");
  5372. editToolbar.addEventListener("contextmenu", noContextMenu, {
  5373. signal: this.#uiManager._signal
  5374. });
  5375. const buttons = this.#buttons = document.createElement("div");
  5376. buttons.className = "buttons";
  5377. editToolbar.append(buttons);
  5378. this.#addHighlightButton();
  5379. return editToolbar;
  5380. }
  5381. #getLastPoint(boxes, isLTR) {
  5382. let lastY = 0;
  5383. let lastX = 0;
  5384. for (const box of boxes) {
  5385. const y = box.y + box.height;
  5386. if (y < lastY) {
  5387. continue;
  5388. }
  5389. const x = box.x + (isLTR ? box.width : 0);
  5390. if (y > lastY) {
  5391. lastX = x;
  5392. lastY = y;
  5393. continue;
  5394. }
  5395. if (isLTR) {
  5396. if (x > lastX) {
  5397. lastX = x;
  5398. }
  5399. } else if (x < lastX) {
  5400. lastX = x;
  5401. }
  5402. }
  5403. return [isLTR ? 1 - lastX : lastX, lastY];
  5404. }
  5405. show(parent, boxes, isLTR) {
  5406. const [x, y] = this.#getLastPoint(boxes, isLTR);
  5407. const {
  5408. style
  5409. } = this.#toolbar ||= this.#render();
  5410. parent.append(this.#toolbar);
  5411. style.insetInlineEnd = `${100 * x}%`;
  5412. style.top = `calc(${100 * y}% + var(--editor-toolbar-vert-offset))`;
  5413. }
  5414. hide() {
  5415. this.#toolbar.remove();
  5416. }
  5417. #addHighlightButton() {
  5418. const button = document.createElement("button");
  5419. button.className = "highlightButton";
  5420. button.tabIndex = 0;
  5421. button.setAttribute("data-l10n-id", `pdfjs-highlight-floating-button1`);
  5422. const span = document.createElement("span");
  5423. button.append(span);
  5424. span.className = "visuallyHidden";
  5425. span.setAttribute("data-l10n-id", "pdfjs-highlight-floating-button-label");
  5426. const signal = this.#uiManager._signal;
  5427. button.addEventListener("contextmenu", noContextMenu, {
  5428. signal
  5429. });
  5430. button.addEventListener("click", () => {
  5431. this.#uiManager.highlightSelection("floating_button");
  5432. }, {
  5433. signal
  5434. });
  5435. this.#buttons.append(button);
  5436. }
  5437. }
  5438. ;// ./src/display/editor/tools.js
  5439. function bindEvents(obj, element, names) {
  5440. for (const name of names) {
  5441. element.addEventListener(name, obj[name].bind(obj));
  5442. }
  5443. }
  5444. function opacityToHex(opacity) {
  5445. return Math.round(Math.min(255, Math.max(1, 255 * opacity))).toString(16).padStart(2, "0");
  5446. }
  5447. class IdManager {
  5448. #id = 0;
  5449. get id() {
  5450. return `${AnnotationEditorPrefix}${this.#id++}`;
  5451. }
  5452. }
  5453. class ImageManager {
  5454. #baseId = getUuid();
  5455. #id = 0;
  5456. #cache = null;
  5457. static get _isSVGFittingCanvas() {
  5458. const svg = `data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>`;
  5459. const canvas = new OffscreenCanvas(1, 3);
  5460. const ctx = canvas.getContext("2d", {
  5461. willReadFrequently: true
  5462. });
  5463. const image = new Image();
  5464. image.src = svg;
  5465. const promise = image.decode().then(() => {
  5466. ctx.drawImage(image, 0, 0, 1, 1, 0, 0, 1, 3);
  5467. return new Uint32Array(ctx.getImageData(0, 0, 1, 1).data.buffer)[0] === 0;
  5468. });
  5469. return shadow(this, "_isSVGFittingCanvas", promise);
  5470. }
  5471. async #get(key, rawData) {
  5472. this.#cache ||= new Map();
  5473. let data = this.#cache.get(key);
  5474. if (data === null) {
  5475. return null;
  5476. }
  5477. if (data?.bitmap) {
  5478. data.refCounter += 1;
  5479. return data;
  5480. }
  5481. try {
  5482. data ||= {
  5483. bitmap: null,
  5484. id: `image_${this.#baseId}_${this.#id++}`,
  5485. refCounter: 0,
  5486. isSvg: false
  5487. };
  5488. let image;
  5489. if (typeof rawData === "string") {
  5490. data.url = rawData;
  5491. image = await fetchData(rawData, "blob");
  5492. } else if (rawData instanceof File) {
  5493. image = data.file = rawData;
  5494. } else if (rawData instanceof Blob) {
  5495. image = rawData;
  5496. }
  5497. if (image.type === "image/svg+xml") {
  5498. const mustRemoveAspectRatioPromise = ImageManager._isSVGFittingCanvas;
  5499. const fileReader = new FileReader();
  5500. const imageElement = new Image();
  5501. const imagePromise = new Promise((resolve, reject) => {
  5502. imageElement.onload = () => {
  5503. data.bitmap = imageElement;
  5504. data.isSvg = true;
  5505. resolve();
  5506. };
  5507. fileReader.onload = async () => {
  5508. const url = data.svgUrl = fileReader.result;
  5509. imageElement.src = (await mustRemoveAspectRatioPromise) ? `${url}#svgView(preserveAspectRatio(none))` : url;
  5510. };
  5511. imageElement.onerror = fileReader.onerror = reject;
  5512. });
  5513. fileReader.readAsDataURL(image);
  5514. await imagePromise;
  5515. } else {
  5516. data.bitmap = await createImageBitmap(image);
  5517. }
  5518. data.refCounter = 1;
  5519. } catch (e) {
  5520. console.error(e);
  5521. data = null;
  5522. }
  5523. this.#cache.set(key, data);
  5524. if (data) {
  5525. this.#cache.set(data.id, data);
  5526. }
  5527. return data;
  5528. }
  5529. async getFromFile(file) {
  5530. const {
  5531. lastModified,
  5532. name,
  5533. size,
  5534. type
  5535. } = file;
  5536. return this.#get(`${lastModified}_${name}_${size}_${type}`, file);
  5537. }
  5538. async getFromUrl(url) {
  5539. return this.#get(url, url);
  5540. }
  5541. async getFromBlob(id, blobPromise) {
  5542. const blob = await blobPromise;
  5543. return this.#get(id, blob);
  5544. }
  5545. async getFromId(id) {
  5546. this.#cache ||= new Map();
  5547. const data = this.#cache.get(id);
  5548. if (!data) {
  5549. return null;
  5550. }
  5551. if (data.bitmap) {
  5552. data.refCounter += 1;
  5553. return data;
  5554. }
  5555. if (data.file) {
  5556. return this.getFromFile(data.file);
  5557. }
  5558. if (data.blobPromise) {
  5559. const {
  5560. blobPromise
  5561. } = data;
  5562. delete data.blobPromise;
  5563. return this.getFromBlob(data.id, blobPromise);
  5564. }
  5565. return this.getFromUrl(data.url);
  5566. }
  5567. getFromCanvas(id, canvas) {
  5568. this.#cache ||= new Map();
  5569. let data = this.#cache.get(id);
  5570. if (data?.bitmap) {
  5571. data.refCounter += 1;
  5572. return data;
  5573. }
  5574. const offscreen = new OffscreenCanvas(canvas.width, canvas.height);
  5575. const ctx = offscreen.getContext("2d");
  5576. ctx.drawImage(canvas, 0, 0);
  5577. data = {
  5578. bitmap: offscreen.transferToImageBitmap(),
  5579. id: `image_${this.#baseId}_${this.#id++}`,
  5580. refCounter: 1,
  5581. isSvg: false
  5582. };
  5583. this.#cache.set(id, data);
  5584. this.#cache.set(data.id, data);
  5585. return data;
  5586. }
  5587. getSvgUrl(id) {
  5588. const data = this.#cache.get(id);
  5589. if (!data?.isSvg) {
  5590. return null;
  5591. }
  5592. return data.svgUrl;
  5593. }
  5594. deleteId(id) {
  5595. this.#cache ||= new Map();
  5596. const data = this.#cache.get(id);
  5597. if (!data) {
  5598. return;
  5599. }
  5600. data.refCounter -= 1;
  5601. if (data.refCounter !== 0) {
  5602. return;
  5603. }
  5604. const {
  5605. bitmap
  5606. } = data;
  5607. if (!data.url && !data.file) {
  5608. const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
  5609. const ctx = canvas.getContext("bitmaprenderer");
  5610. ctx.transferFromImageBitmap(bitmap);
  5611. data.blobPromise = canvas.convertToBlob();
  5612. }
  5613. bitmap.close?.();
  5614. data.bitmap = null;
  5615. }
  5616. isValidId(id) {
  5617. return id.startsWith(`image_${this.#baseId}_`);
  5618. }
  5619. }
  5620. class CommandManager {
  5621. #commands = [];
  5622. #locked = false;
  5623. #maxSize;
  5624. #position = -1;
  5625. constructor(maxSize = 128) {
  5626. this.#maxSize = maxSize;
  5627. }
  5628. add({
  5629. cmd,
  5630. undo,
  5631. post,
  5632. mustExec,
  5633. type = NaN,
  5634. overwriteIfSameType = false,
  5635. keepUndo = false
  5636. }) {
  5637. if (mustExec) {
  5638. cmd();
  5639. }
  5640. if (this.#locked) {
  5641. return;
  5642. }
  5643. const save = {
  5644. cmd,
  5645. undo,
  5646. post,
  5647. type
  5648. };
  5649. if (this.#position === -1) {
  5650. if (this.#commands.length > 0) {
  5651. this.#commands.length = 0;
  5652. }
  5653. this.#position = 0;
  5654. this.#commands.push(save);
  5655. return;
  5656. }
  5657. if (overwriteIfSameType && this.#commands[this.#position].type === type) {
  5658. if (keepUndo) {
  5659. save.undo = this.#commands[this.#position].undo;
  5660. }
  5661. this.#commands[this.#position] = save;
  5662. return;
  5663. }
  5664. const next = this.#position + 1;
  5665. if (next === this.#maxSize) {
  5666. this.#commands.splice(0, 1);
  5667. } else {
  5668. this.#position = next;
  5669. if (next < this.#commands.length) {
  5670. this.#commands.splice(next);
  5671. }
  5672. }
  5673. this.#commands.push(save);
  5674. }
  5675. undo() {
  5676. if (this.#position === -1) {
  5677. return;
  5678. }
  5679. this.#locked = true;
  5680. const {
  5681. undo,
  5682. post
  5683. } = this.#commands[this.#position];
  5684. undo();
  5685. post?.();
  5686. this.#locked = false;
  5687. this.#position -= 1;
  5688. }
  5689. redo() {
  5690. if (this.#position < this.#commands.length - 1) {
  5691. this.#position += 1;
  5692. this.#locked = true;
  5693. const {
  5694. cmd,
  5695. post
  5696. } = this.#commands[this.#position];
  5697. cmd();
  5698. post?.();
  5699. this.#locked = false;
  5700. }
  5701. }
  5702. hasSomethingToUndo() {
  5703. return this.#position !== -1;
  5704. }
  5705. hasSomethingToRedo() {
  5706. return this.#position < this.#commands.length - 1;
  5707. }
  5708. destroy() {
  5709. this.#commands = null;
  5710. }
  5711. }
  5712. class KeyboardManager {
  5713. constructor(callbacks) {
  5714. this.buffer = [];
  5715. this.callbacks = new Map();
  5716. this.allKeys = new Set();
  5717. const {
  5718. isMac
  5719. } = util_FeatureTest.platform;
  5720. for (const [keys, callback, options = {}] of callbacks) {
  5721. for (const key of keys) {
  5722. const isMacKey = key.startsWith("mac+");
  5723. if (isMac && isMacKey) {
  5724. this.callbacks.set(key.slice(4), {
  5725. callback,
  5726. options
  5727. });
  5728. this.allKeys.add(key.split("+").at(-1));
  5729. } else if (!isMac && !isMacKey) {
  5730. this.callbacks.set(key, {
  5731. callback,
  5732. options
  5733. });
  5734. this.allKeys.add(key.split("+").at(-1));
  5735. }
  5736. }
  5737. }
  5738. }
  5739. #serialize(event) {
  5740. if (event.altKey) {
  5741. this.buffer.push("alt");
  5742. }
  5743. if (event.ctrlKey) {
  5744. this.buffer.push("ctrl");
  5745. }
  5746. if (event.metaKey) {
  5747. this.buffer.push("meta");
  5748. }
  5749. if (event.shiftKey) {
  5750. this.buffer.push("shift");
  5751. }
  5752. this.buffer.push(event.key);
  5753. const str = this.buffer.join("+");
  5754. this.buffer.length = 0;
  5755. return str;
  5756. }
  5757. exec(self, event) {
  5758. if (!this.allKeys.has(event.key)) {
  5759. return;
  5760. }
  5761. const info = this.callbacks.get(this.#serialize(event));
  5762. if (!info) {
  5763. return;
  5764. }
  5765. const {
  5766. callback,
  5767. options: {
  5768. bubbles = false,
  5769. args = [],
  5770. checker = null
  5771. }
  5772. } = info;
  5773. if (checker && !checker(self, event)) {
  5774. return;
  5775. }
  5776. callback.bind(self, ...args, event)();
  5777. if (!bubbles) {
  5778. event.stopPropagation();
  5779. event.preventDefault();
  5780. }
  5781. }
  5782. }
  5783. class ColorManager {
  5784. static _colorsMapping = new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]);
  5785. get _colors() {
  5786. const colors = new Map([["CanvasText", null], ["Canvas", null]]);
  5787. getColorValues(colors);
  5788. return shadow(this, "_colors", colors);
  5789. }
  5790. convert(color) {
  5791. const rgb = getRGB(color);
  5792. if (!window.matchMedia("(forced-colors: active)").matches) {
  5793. return rgb;
  5794. }
  5795. for (const [name, RGB] of this._colors) {
  5796. if (RGB.every((x, i) => x === rgb[i])) {
  5797. return ColorManager._colorsMapping.get(name);
  5798. }
  5799. }
  5800. return rgb;
  5801. }
  5802. getHexCode(name) {
  5803. const rgb = this._colors.get(name);
  5804. if (!rgb) {
  5805. return name;
  5806. }
  5807. return Util.makeHexColor(...rgb);
  5808. }
  5809. }
  5810. class AnnotationEditorUIManager {
  5811. #abortController = new AbortController();
  5812. #activeEditor = null;
  5813. #allEditors = new Map();
  5814. #allLayers = new Map();
  5815. #altTextManager = null;
  5816. #annotationStorage = null;
  5817. #changedExistingAnnotations = null;
  5818. #commandManager = new CommandManager();
  5819. #copyPasteAC = null;
  5820. #currentPageIndex = 0;
  5821. #deletedAnnotationsElementIds = new Set();
  5822. #draggingEditors = null;
  5823. #editorTypes = null;
  5824. #editorsToRescale = new Set();
  5825. #enableHighlightFloatingButton = false;
  5826. #enableUpdatedAddImage = false;
  5827. #enableNewAltTextWhenAddingImage = false;
  5828. #filterFactory = null;
  5829. #focusMainContainerTimeoutId = null;
  5830. #focusManagerAC = null;
  5831. #highlightColors = null;
  5832. #highlightWhenShiftUp = false;
  5833. #highlightToolbar = null;
  5834. #idManager = new IdManager();
  5835. #isEnabled = false;
  5836. #isWaiting = false;
  5837. #keyboardManagerAC = null;
  5838. #lastActiveElement = null;
  5839. #mainHighlightColorPicker = null;
  5840. #mlManager = null;
  5841. #mode = AnnotationEditorType.NONE;
  5842. #selectedEditors = new Set();
  5843. #selectedTextNode = null;
  5844. #pageColors = null;
  5845. #showAllStates = null;
  5846. #previousStates = {
  5847. isEditing: false,
  5848. isEmpty: true,
  5849. hasSomethingToUndo: false,
  5850. hasSomethingToRedo: false,
  5851. hasSelectedEditor: false,
  5852. hasSelectedText: false
  5853. };
  5854. #translation = [0, 0];
  5855. #translationTimeoutId = null;
  5856. #container = null;
  5857. #viewer = null;
  5858. #updateModeCapability = null;
  5859. static TRANSLATE_SMALL = 1;
  5860. static TRANSLATE_BIG = 10;
  5861. static get _keyboardManager() {
  5862. const proto = AnnotationEditorUIManager.prototype;
  5863. const arrowChecker = self => self.#container.contains(document.activeElement) && document.activeElement.tagName !== "BUTTON" && self.hasSomethingToControl();
  5864. const textInputChecker = (_self, {
  5865. target: el
  5866. }) => {
  5867. if (el instanceof HTMLInputElement) {
  5868. const {
  5869. type
  5870. } = el;
  5871. return type !== "text" && type !== "number";
  5872. }
  5873. return true;
  5874. };
  5875. const small = this.TRANSLATE_SMALL;
  5876. const big = this.TRANSLATE_BIG;
  5877. return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+a", "mac+meta+a"], proto.selectAll, {
  5878. checker: textInputChecker
  5879. }], [["ctrl+z", "mac+meta+z"], proto.undo, {
  5880. checker: textInputChecker
  5881. }], [["ctrl+y", "ctrl+shift+z", "mac+meta+shift+z", "ctrl+shift+Z", "mac+meta+shift+Z"], proto.redo, {
  5882. checker: textInputChecker
  5883. }], [["Backspace", "alt+Backspace", "ctrl+Backspace", "shift+Backspace", "mac+Backspace", "mac+alt+Backspace", "mac+ctrl+Backspace", "Delete", "ctrl+Delete", "shift+Delete", "mac+Delete"], proto.delete, {
  5884. checker: textInputChecker
  5885. }], [["Enter", "mac+Enter"], proto.addNewEditorFromKeyboard, {
  5886. checker: (self, {
  5887. target: el
  5888. }) => !(el instanceof HTMLButtonElement) && self.#container.contains(el) && !self.isEnterHandled
  5889. }], [[" ", "mac+ "], proto.addNewEditorFromKeyboard, {
  5890. checker: (self, {
  5891. target: el
  5892. }) => !(el instanceof HTMLButtonElement) && self.#container.contains(document.activeElement)
  5893. }], [["Escape", "mac+Escape"], proto.unselectAll], [["ArrowLeft", "mac+ArrowLeft"], proto.translateSelectedEditors, {
  5894. args: [-small, 0],
  5895. checker: arrowChecker
  5896. }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto.translateSelectedEditors, {
  5897. args: [-big, 0],
  5898. checker: arrowChecker
  5899. }], [["ArrowRight", "mac+ArrowRight"], proto.translateSelectedEditors, {
  5900. args: [small, 0],
  5901. checker: arrowChecker
  5902. }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto.translateSelectedEditors, {
  5903. args: [big, 0],
  5904. checker: arrowChecker
  5905. }], [["ArrowUp", "mac+ArrowUp"], proto.translateSelectedEditors, {
  5906. args: [0, -small],
  5907. checker: arrowChecker
  5908. }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto.translateSelectedEditors, {
  5909. args: [0, -big],
  5910. checker: arrowChecker
  5911. }], [["ArrowDown", "mac+ArrowDown"], proto.translateSelectedEditors, {
  5912. args: [0, small],
  5913. checker: arrowChecker
  5914. }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto.translateSelectedEditors, {
  5915. args: [0, big],
  5916. checker: arrowChecker
  5917. }]]));
  5918. }
  5919. constructor(container, viewer, altTextManager, eventBus, pdfDocument, pageColors, highlightColors, enableHighlightFloatingButton, enableUpdatedAddImage, enableNewAltTextWhenAddingImage, mlManager) {
  5920. const signal = this._signal = this.#abortController.signal;
  5921. this.#container = container;
  5922. this.#viewer = viewer;
  5923. this.#altTextManager = altTextManager;
  5924. this._eventBus = eventBus;
  5925. eventBus._on("editingaction", this.onEditingAction.bind(this), {
  5926. signal
  5927. });
  5928. eventBus._on("pagechanging", this.onPageChanging.bind(this), {
  5929. signal
  5930. });
  5931. eventBus._on("scalechanging", this.onScaleChanging.bind(this), {
  5932. signal
  5933. });
  5934. eventBus._on("rotationchanging", this.onRotationChanging.bind(this), {
  5935. signal
  5936. });
  5937. eventBus._on("setpreference", this.onSetPreference.bind(this), {
  5938. signal
  5939. });
  5940. eventBus._on("switchannotationeditorparams", evt => this.updateParams(evt.type, evt.value), {
  5941. signal
  5942. });
  5943. this.#addSelectionListener();
  5944. this.#addDragAndDropListeners();
  5945. this.#addKeyboardManager();
  5946. this.#annotationStorage = pdfDocument.annotationStorage;
  5947. this.#filterFactory = pdfDocument.filterFactory;
  5948. this.#pageColors = pageColors;
  5949. this.#highlightColors = highlightColors || null;
  5950. this.#enableHighlightFloatingButton = enableHighlightFloatingButton;
  5951. this.#enableUpdatedAddImage = enableUpdatedAddImage;
  5952. this.#enableNewAltTextWhenAddingImage = enableNewAltTextWhenAddingImage;
  5953. this.#mlManager = mlManager || null;
  5954. this.viewParameters = {
  5955. realScale: PixelsPerInch.PDF_TO_CSS_UNITS,
  5956. rotation: 0
  5957. };
  5958. this.isShiftKeyDown = false;
  5959. }
  5960. destroy() {
  5961. this.#updateModeCapability?.resolve();
  5962. this.#updateModeCapability = null;
  5963. this.#abortController?.abort();
  5964. this.#abortController = null;
  5965. this._signal = null;
  5966. for (const layer of this.#allLayers.values()) {
  5967. layer.destroy();
  5968. }
  5969. this.#allLayers.clear();
  5970. this.#allEditors.clear();
  5971. this.#editorsToRescale.clear();
  5972. this.#activeEditor = null;
  5973. this.#selectedEditors.clear();
  5974. this.#commandManager.destroy();
  5975. this.#altTextManager?.destroy();
  5976. this.#highlightToolbar?.hide();
  5977. this.#highlightToolbar = null;
  5978. if (this.#focusMainContainerTimeoutId) {
  5979. clearTimeout(this.#focusMainContainerTimeoutId);
  5980. this.#focusMainContainerTimeoutId = null;
  5981. }
  5982. if (this.#translationTimeoutId) {
  5983. clearTimeout(this.#translationTimeoutId);
  5984. this.#translationTimeoutId = null;
  5985. }
  5986. }
  5987. combinedSignal(ac) {
  5988. return AbortSignal.any([this._signal, ac.signal]);
  5989. }
  5990. get mlManager() {
  5991. return this.#mlManager;
  5992. }
  5993. get useNewAltTextFlow() {
  5994. return this.#enableUpdatedAddImage;
  5995. }
  5996. get useNewAltTextWhenAddingImage() {
  5997. return this.#enableNewAltTextWhenAddingImage;
  5998. }
  5999. get hcmFilter() {
  6000. return shadow(this, "hcmFilter", this.#pageColors ? this.#filterFactory.addHCMFilter(this.#pageColors.foreground, this.#pageColors.background) : "none");
  6001. }
  6002. get direction() {
  6003. return shadow(this, "direction", getComputedStyle(this.#container).direction);
  6004. }
  6005. get highlightColors() {
  6006. return shadow(this, "highlightColors", this.#highlightColors ? new Map(this.#highlightColors.split(",").map(pair => pair.split("=").map(x => x.trim()))) : null);
  6007. }
  6008. get highlightColorNames() {
  6009. return shadow(this, "highlightColorNames", this.highlightColors ? new Map(Array.from(this.highlightColors, e => e.reverse())) : null);
  6010. }
  6011. setMainHighlightColorPicker(colorPicker) {
  6012. this.#mainHighlightColorPicker = colorPicker;
  6013. }
  6014. editAltText(editor, firstTime = false) {
  6015. this.#altTextManager?.editAltText(this, editor, firstTime);
  6016. }
  6017. switchToMode(mode, callback) {
  6018. this._eventBus.on("annotationeditormodechanged", callback, {
  6019. once: true,
  6020. signal: this._signal
  6021. });
  6022. this._eventBus.dispatch("showannotationeditorui", {
  6023. source: this,
  6024. mode
  6025. });
  6026. }
  6027. setPreference(name, value) {
  6028. this._eventBus.dispatch("setpreference", {
  6029. source: this,
  6030. name,
  6031. value
  6032. });
  6033. }
  6034. onSetPreference({
  6035. name,
  6036. value
  6037. }) {
  6038. switch (name) {
  6039. case "enableNewAltTextWhenAddingImage":
  6040. this.#enableNewAltTextWhenAddingImage = value;
  6041. break;
  6042. }
  6043. }
  6044. onPageChanging({
  6045. pageNumber
  6046. }) {
  6047. this.#currentPageIndex = pageNumber - 1;
  6048. }
  6049. focusMainContainer() {
  6050. this.#container.focus();
  6051. }
  6052. findParent(x, y) {
  6053. for (const layer of this.#allLayers.values()) {
  6054. const {
  6055. x: layerX,
  6056. y: layerY,
  6057. width,
  6058. height
  6059. } = layer.div.getBoundingClientRect();
  6060. if (x >= layerX && x <= layerX + width && y >= layerY && y <= layerY + height) {
  6061. return layer;
  6062. }
  6063. }
  6064. return null;
  6065. }
  6066. disableUserSelect(value = false) {
  6067. this.#viewer.classList.toggle("noUserSelect", value);
  6068. }
  6069. addShouldRescale(editor) {
  6070. this.#editorsToRescale.add(editor);
  6071. }
  6072. removeShouldRescale(editor) {
  6073. this.#editorsToRescale.delete(editor);
  6074. }
  6075. onScaleChanging({
  6076. scale
  6077. }) {
  6078. this.commitOrRemove();
  6079. this.viewParameters.realScale = scale * PixelsPerInch.PDF_TO_CSS_UNITS;
  6080. for (const editor of this.#editorsToRescale) {
  6081. editor.onScaleChanging();
  6082. }
  6083. }
  6084. onRotationChanging({
  6085. pagesRotation
  6086. }) {
  6087. this.commitOrRemove();
  6088. this.viewParameters.rotation = pagesRotation;
  6089. }
  6090. #getAnchorElementForSelection({
  6091. anchorNode
  6092. }) {
  6093. return anchorNode.nodeType === Node.TEXT_NODE ? anchorNode.parentElement : anchorNode;
  6094. }
  6095. #getLayerForTextLayer(textLayer) {
  6096. const {
  6097. currentLayer
  6098. } = this;
  6099. if (currentLayer.hasTextLayer(textLayer)) {
  6100. return currentLayer;
  6101. }
  6102. for (const layer of this.#allLayers.values()) {
  6103. if (layer.hasTextLayer(textLayer)) {
  6104. return layer;
  6105. }
  6106. }
  6107. return null;
  6108. }
  6109. highlightSelection(methodOfCreation = "") {
  6110. const selection = document.getSelection();
  6111. if (!selection || selection.isCollapsed) {
  6112. return;
  6113. }
  6114. const {
  6115. anchorNode,
  6116. anchorOffset,
  6117. focusNode,
  6118. focusOffset
  6119. } = selection;
  6120. const text = selection.toString();
  6121. const anchorElement = this.#getAnchorElementForSelection(selection);
  6122. const textLayer = anchorElement.closest(".textLayer");
  6123. const boxes = this.getSelectionBoxes(textLayer);
  6124. if (!boxes) {
  6125. return;
  6126. }
  6127. selection.empty();
  6128. const layer = this.#getLayerForTextLayer(textLayer);
  6129. const isNoneMode = this.#mode === AnnotationEditorType.NONE;
  6130. const callback = () => {
  6131. layer?.createAndAddNewEditor({
  6132. x: 0,
  6133. y: 0
  6134. }, false, {
  6135. methodOfCreation,
  6136. boxes,
  6137. anchorNode,
  6138. anchorOffset,
  6139. focusNode,
  6140. focusOffset,
  6141. text
  6142. });
  6143. if (isNoneMode) {
  6144. this.showAllEditors("highlight", true, true);
  6145. }
  6146. };
  6147. if (isNoneMode) {
  6148. this.switchToMode(AnnotationEditorType.HIGHLIGHT, callback);
  6149. return;
  6150. }
  6151. callback();
  6152. }
  6153. #displayHighlightToolbar() {
  6154. const selection = document.getSelection();
  6155. if (!selection || selection.isCollapsed) {
  6156. return;
  6157. }
  6158. const anchorElement = this.#getAnchorElementForSelection(selection);
  6159. const textLayer = anchorElement.closest(".textLayer");
  6160. const boxes = this.getSelectionBoxes(textLayer);
  6161. if (!boxes) {
  6162. return;
  6163. }
  6164. this.#highlightToolbar ||= new HighlightToolbar(this);
  6165. this.#highlightToolbar.show(textLayer, boxes, this.direction === "ltr");
  6166. }
  6167. addToAnnotationStorage(editor) {
  6168. if (!editor.isEmpty() && this.#annotationStorage && !this.#annotationStorage.has(editor.id)) {
  6169. this.#annotationStorage.setValue(editor.id, editor);
  6170. }
  6171. }
  6172. #selectionChange() {
  6173. const selection = document.getSelection();
  6174. if (!selection || selection.isCollapsed) {
  6175. if (this.#selectedTextNode) {
  6176. this.#highlightToolbar?.hide();
  6177. this.#selectedTextNode = null;
  6178. this.#dispatchUpdateStates({
  6179. hasSelectedText: false
  6180. });
  6181. }
  6182. return;
  6183. }
  6184. const {
  6185. anchorNode
  6186. } = selection;
  6187. if (anchorNode === this.#selectedTextNode) {
  6188. return;
  6189. }
  6190. const anchorElement = this.#getAnchorElementForSelection(selection);
  6191. const textLayer = anchorElement.closest(".textLayer");
  6192. if (!textLayer) {
  6193. if (this.#selectedTextNode) {
  6194. this.#highlightToolbar?.hide();
  6195. this.#selectedTextNode = null;
  6196. this.#dispatchUpdateStates({
  6197. hasSelectedText: false
  6198. });
  6199. }
  6200. return;
  6201. }
  6202. this.#highlightToolbar?.hide();
  6203. this.#selectedTextNode = anchorNode;
  6204. this.#dispatchUpdateStates({
  6205. hasSelectedText: true
  6206. });
  6207. if (this.#mode !== AnnotationEditorType.HIGHLIGHT && this.#mode !== AnnotationEditorType.NONE) {
  6208. return;
  6209. }
  6210. if (this.#mode === AnnotationEditorType.HIGHLIGHT) {
  6211. this.showAllEditors("highlight", true, true);
  6212. }
  6213. this.#highlightWhenShiftUp = this.isShiftKeyDown;
  6214. if (!this.isShiftKeyDown) {
  6215. const activeLayer = this.#mode === AnnotationEditorType.HIGHLIGHT ? this.#getLayerForTextLayer(textLayer) : null;
  6216. activeLayer?.toggleDrawing();
  6217. const ac = new AbortController();
  6218. const signal = this.combinedSignal(ac);
  6219. const pointerup = e => {
  6220. if (e.type === "pointerup" && e.button !== 0) {
  6221. return;
  6222. }
  6223. ac.abort();
  6224. activeLayer?.toggleDrawing(true);
  6225. if (e.type === "pointerup") {
  6226. this.#onSelectEnd("main_toolbar");
  6227. }
  6228. };
  6229. window.addEventListener("pointerup", pointerup, {
  6230. signal
  6231. });
  6232. window.addEventListener("blur", pointerup, {
  6233. signal
  6234. });
  6235. }
  6236. }
  6237. #onSelectEnd(methodOfCreation = "") {
  6238. if (this.#mode === AnnotationEditorType.HIGHLIGHT) {
  6239. this.highlightSelection(methodOfCreation);
  6240. } else if (this.#enableHighlightFloatingButton) {
  6241. this.#displayHighlightToolbar();
  6242. }
  6243. }
  6244. #addSelectionListener() {
  6245. document.addEventListener("selectionchange", this.#selectionChange.bind(this), {
  6246. signal: this._signal
  6247. });
  6248. }
  6249. #addFocusManager() {
  6250. if (this.#focusManagerAC) {
  6251. return;
  6252. }
  6253. this.#focusManagerAC = new AbortController();
  6254. const signal = this.combinedSignal(this.#focusManagerAC);
  6255. window.addEventListener("focus", this.focus.bind(this), {
  6256. signal
  6257. });
  6258. window.addEventListener("blur", this.blur.bind(this), {
  6259. signal
  6260. });
  6261. }
  6262. #removeFocusManager() {
  6263. this.#focusManagerAC?.abort();
  6264. this.#focusManagerAC = null;
  6265. }
  6266. blur() {
  6267. this.isShiftKeyDown = false;
  6268. if (this.#highlightWhenShiftUp) {
  6269. this.#highlightWhenShiftUp = false;
  6270. this.#onSelectEnd("main_toolbar");
  6271. }
  6272. if (!this.hasSelection) {
  6273. return;
  6274. }
  6275. const {
  6276. activeElement
  6277. } = document;
  6278. for (const editor of this.#selectedEditors) {
  6279. if (editor.div.contains(activeElement)) {
  6280. this.#lastActiveElement = [editor, activeElement];
  6281. editor._focusEventsAllowed = false;
  6282. break;
  6283. }
  6284. }
  6285. }
  6286. focus() {
  6287. if (!this.#lastActiveElement) {
  6288. return;
  6289. }
  6290. const [lastEditor, lastActiveElement] = this.#lastActiveElement;
  6291. this.#lastActiveElement = null;
  6292. lastActiveElement.addEventListener("focusin", () => {
  6293. lastEditor._focusEventsAllowed = true;
  6294. }, {
  6295. once: true,
  6296. signal: this._signal
  6297. });
  6298. lastActiveElement.focus();
  6299. }
  6300. #addKeyboardManager() {
  6301. if (this.#keyboardManagerAC) {
  6302. return;
  6303. }
  6304. this.#keyboardManagerAC = new AbortController();
  6305. const signal = this.combinedSignal(this.#keyboardManagerAC);
  6306. window.addEventListener("keydown", this.keydown.bind(this), {
  6307. signal
  6308. });
  6309. window.addEventListener("keyup", this.keyup.bind(this), {
  6310. signal
  6311. });
  6312. }
  6313. #removeKeyboardManager() {
  6314. this.#keyboardManagerAC?.abort();
  6315. this.#keyboardManagerAC = null;
  6316. }
  6317. #addCopyPasteListeners() {
  6318. if (this.#copyPasteAC) {
  6319. return;
  6320. }
  6321. this.#copyPasteAC = new AbortController();
  6322. const signal = this.combinedSignal(this.#copyPasteAC);
  6323. document.addEventListener("copy", this.copy.bind(this), {
  6324. signal
  6325. });
  6326. document.addEventListener("cut", this.cut.bind(this), {
  6327. signal
  6328. });
  6329. document.addEventListener("paste", this.paste.bind(this), {
  6330. signal
  6331. });
  6332. }
  6333. #removeCopyPasteListeners() {
  6334. this.#copyPasteAC?.abort();
  6335. this.#copyPasteAC = null;
  6336. }
  6337. #addDragAndDropListeners() {
  6338. const signal = this._signal;
  6339. document.addEventListener("dragover", this.dragOver.bind(this), {
  6340. signal
  6341. });
  6342. document.addEventListener("drop", this.drop.bind(this), {
  6343. signal
  6344. });
  6345. }
  6346. addEditListeners() {
  6347. this.#addKeyboardManager();
  6348. this.#addCopyPasteListeners();
  6349. }
  6350. removeEditListeners() {
  6351. this.#removeKeyboardManager();
  6352. this.#removeCopyPasteListeners();
  6353. }
  6354. dragOver(event) {
  6355. for (const {
  6356. type
  6357. } of event.dataTransfer.items) {
  6358. for (const editorType of this.#editorTypes) {
  6359. if (editorType.isHandlingMimeForPasting(type)) {
  6360. event.dataTransfer.dropEffect = "copy";
  6361. event.preventDefault();
  6362. return;
  6363. }
  6364. }
  6365. }
  6366. }
  6367. drop(event) {
  6368. for (const item of event.dataTransfer.items) {
  6369. for (const editorType of this.#editorTypes) {
  6370. if (editorType.isHandlingMimeForPasting(item.type)) {
  6371. editorType.paste(item, this.currentLayer);
  6372. event.preventDefault();
  6373. return;
  6374. }
  6375. }
  6376. }
  6377. }
  6378. copy(event) {
  6379. event.preventDefault();
  6380. this.#activeEditor?.commitOrRemove();
  6381. if (!this.hasSelection) {
  6382. return;
  6383. }
  6384. const editors = [];
  6385. for (const editor of this.#selectedEditors) {
  6386. const serialized = editor.serialize(true);
  6387. if (serialized) {
  6388. editors.push(serialized);
  6389. }
  6390. }
  6391. if (editors.length === 0) {
  6392. return;
  6393. }
  6394. event.clipboardData.setData("application/pdfjs", JSON.stringify(editors));
  6395. }
  6396. cut(event) {
  6397. this.copy(event);
  6398. this.delete();
  6399. }
  6400. async paste(event) {
  6401. event.preventDefault();
  6402. const {
  6403. clipboardData
  6404. } = event;
  6405. for (const item of clipboardData.items) {
  6406. for (const editorType of this.#editorTypes) {
  6407. if (editorType.isHandlingMimeForPasting(item.type)) {
  6408. editorType.paste(item, this.currentLayer);
  6409. return;
  6410. }
  6411. }
  6412. }
  6413. let data = clipboardData.getData("application/pdfjs");
  6414. if (!data) {
  6415. return;
  6416. }
  6417. try {
  6418. data = JSON.parse(data);
  6419. } catch (ex) {
  6420. warn(`paste: "${ex.message}".`);
  6421. return;
  6422. }
  6423. if (!Array.isArray(data)) {
  6424. return;
  6425. }
  6426. this.unselectAll();
  6427. const layer = this.currentLayer;
  6428. try {
  6429. const newEditors = [];
  6430. for (const editor of data) {
  6431. const deserializedEditor = await layer.deserialize(editor);
  6432. if (!deserializedEditor) {
  6433. return;
  6434. }
  6435. newEditors.push(deserializedEditor);
  6436. }
  6437. const cmd = () => {
  6438. for (const editor of newEditors) {
  6439. this.#addEditorToLayer(editor);
  6440. }
  6441. this.#selectEditors(newEditors);
  6442. };
  6443. const undo = () => {
  6444. for (const editor of newEditors) {
  6445. editor.remove();
  6446. }
  6447. };
  6448. this.addCommands({
  6449. cmd,
  6450. undo,
  6451. mustExec: true
  6452. });
  6453. } catch (ex) {
  6454. warn(`paste: "${ex.message}".`);
  6455. }
  6456. }
  6457. keydown(event) {
  6458. if (!this.isShiftKeyDown && event.key === "Shift") {
  6459. this.isShiftKeyDown = true;
  6460. }
  6461. if (this.#mode !== AnnotationEditorType.NONE && !this.isEditorHandlingKeyboard) {
  6462. AnnotationEditorUIManager._keyboardManager.exec(this, event);
  6463. }
  6464. }
  6465. keyup(event) {
  6466. if (this.isShiftKeyDown && event.key === "Shift") {
  6467. this.isShiftKeyDown = false;
  6468. if (this.#highlightWhenShiftUp) {
  6469. this.#highlightWhenShiftUp = false;
  6470. this.#onSelectEnd("main_toolbar");
  6471. }
  6472. }
  6473. }
  6474. onEditingAction({
  6475. name
  6476. }) {
  6477. switch (name) {
  6478. case "undo":
  6479. case "redo":
  6480. case "delete":
  6481. case "selectAll":
  6482. this[name]();
  6483. break;
  6484. case "highlightSelection":
  6485. this.highlightSelection("context_menu");
  6486. break;
  6487. }
  6488. }
  6489. #dispatchUpdateStates(details) {
  6490. const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value);
  6491. if (hasChanged) {
  6492. this._eventBus.dispatch("annotationeditorstateschanged", {
  6493. source: this,
  6494. details: Object.assign(this.#previousStates, details)
  6495. });
  6496. if (this.#mode === AnnotationEditorType.HIGHLIGHT && details.hasSelectedEditor === false) {
  6497. this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_FREE, true]]);
  6498. }
  6499. }
  6500. }
  6501. #dispatchUpdateUI(details) {
  6502. this._eventBus.dispatch("annotationeditorparamschanged", {
  6503. source: this,
  6504. details
  6505. });
  6506. }
  6507. setEditingState(isEditing) {
  6508. if (isEditing) {
  6509. this.#addFocusManager();
  6510. this.#addCopyPasteListeners();
  6511. this.#dispatchUpdateStates({
  6512. isEditing: this.#mode !== AnnotationEditorType.NONE,
  6513. isEmpty: this.#isEmpty(),
  6514. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  6515. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  6516. hasSelectedEditor: false
  6517. });
  6518. } else {
  6519. this.#removeFocusManager();
  6520. this.#removeCopyPasteListeners();
  6521. this.#dispatchUpdateStates({
  6522. isEditing: false
  6523. });
  6524. this.disableUserSelect(false);
  6525. }
  6526. }
  6527. registerEditorTypes(types) {
  6528. if (this.#editorTypes) {
  6529. return;
  6530. }
  6531. this.#editorTypes = types;
  6532. for (const editorType of this.#editorTypes) {
  6533. this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
  6534. }
  6535. }
  6536. getId() {
  6537. return this.#idManager.id;
  6538. }
  6539. get currentLayer() {
  6540. return this.#allLayers.get(this.#currentPageIndex);
  6541. }
  6542. getLayer(pageIndex) {
  6543. return this.#allLayers.get(pageIndex);
  6544. }
  6545. get currentPageIndex() {
  6546. return this.#currentPageIndex;
  6547. }
  6548. addLayer(layer) {
  6549. this.#allLayers.set(layer.pageIndex, layer);
  6550. if (this.#isEnabled) {
  6551. layer.enable();
  6552. } else {
  6553. layer.disable();
  6554. }
  6555. }
  6556. removeLayer(layer) {
  6557. this.#allLayers.delete(layer.pageIndex);
  6558. }
  6559. async updateMode(mode, editId = null, isFromKeyboard = false) {
  6560. if (this.#mode === mode) {
  6561. return;
  6562. }
  6563. if (this.#updateModeCapability) {
  6564. await this.#updateModeCapability.promise;
  6565. if (!this.#updateModeCapability) {
  6566. return;
  6567. }
  6568. }
  6569. this.#updateModeCapability = Promise.withResolvers();
  6570. this.#mode = mode;
  6571. if (mode === AnnotationEditorType.NONE) {
  6572. this.setEditingState(false);
  6573. this.#disableAll();
  6574. this.#updateModeCapability.resolve();
  6575. return;
  6576. }
  6577. this.setEditingState(true);
  6578. await this.#enableAll();
  6579. this.unselectAll();
  6580. for (const layer of this.#allLayers.values()) {
  6581. layer.updateMode(mode);
  6582. }
  6583. if (!editId) {
  6584. if (isFromKeyboard) {
  6585. this.addNewEditorFromKeyboard();
  6586. }
  6587. this.#updateModeCapability.resolve();
  6588. return;
  6589. }
  6590. for (const editor of this.#allEditors.values()) {
  6591. if (editor.annotationElementId === editId) {
  6592. this.setSelected(editor);
  6593. editor.enterInEditMode();
  6594. } else {
  6595. editor.unselect();
  6596. }
  6597. }
  6598. this.#updateModeCapability.resolve();
  6599. }
  6600. addNewEditorFromKeyboard() {
  6601. if (this.currentLayer.canCreateNewEmptyEditor()) {
  6602. this.currentLayer.addNewEditor();
  6603. }
  6604. }
  6605. updateToolbar(mode) {
  6606. if (mode === this.#mode) {
  6607. return;
  6608. }
  6609. this._eventBus.dispatch("switchannotationeditormode", {
  6610. source: this,
  6611. mode
  6612. });
  6613. }
  6614. updateParams(type, value) {
  6615. if (!this.#editorTypes) {
  6616. return;
  6617. }
  6618. switch (type) {
  6619. case AnnotationEditorParamsType.CREATE:
  6620. this.currentLayer.addNewEditor();
  6621. return;
  6622. case AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:
  6623. this.#mainHighlightColorPicker?.updateColor(value);
  6624. break;
  6625. case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:
  6626. this._eventBus.dispatch("reporttelemetry", {
  6627. source: this,
  6628. details: {
  6629. type: "editing",
  6630. data: {
  6631. type: "highlight",
  6632. action: "toggle_visibility"
  6633. }
  6634. }
  6635. });
  6636. (this.#showAllStates ||= new Map()).set(type, value);
  6637. this.showAllEditors("highlight", value);
  6638. break;
  6639. }
  6640. for (const editor of this.#selectedEditors) {
  6641. editor.updateParams(type, value);
  6642. }
  6643. for (const editorType of this.#editorTypes) {
  6644. editorType.updateDefaultParams(type, value);
  6645. }
  6646. }
  6647. showAllEditors(type, visible, updateButton = false) {
  6648. for (const editor of this.#allEditors.values()) {
  6649. if (editor.editorType === type) {
  6650. editor.show(visible);
  6651. }
  6652. }
  6653. const state = this.#showAllStates?.get(AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL) ?? true;
  6654. if (state !== visible) {
  6655. this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL, visible]]);
  6656. }
  6657. }
  6658. enableWaiting(mustWait = false) {
  6659. if (this.#isWaiting === mustWait) {
  6660. return;
  6661. }
  6662. this.#isWaiting = mustWait;
  6663. for (const layer of this.#allLayers.values()) {
  6664. if (mustWait) {
  6665. layer.disableClick();
  6666. } else {
  6667. layer.enableClick();
  6668. }
  6669. layer.div.classList.toggle("waiting", mustWait);
  6670. }
  6671. }
  6672. async #enableAll() {
  6673. if (!this.#isEnabled) {
  6674. this.#isEnabled = true;
  6675. const promises = [];
  6676. for (const layer of this.#allLayers.values()) {
  6677. promises.push(layer.enable());
  6678. }
  6679. await Promise.all(promises);
  6680. for (const editor of this.#allEditors.values()) {
  6681. editor.enable();
  6682. }
  6683. }
  6684. }
  6685. #disableAll() {
  6686. this.unselectAll();
  6687. if (this.#isEnabled) {
  6688. this.#isEnabled = false;
  6689. for (const layer of this.#allLayers.values()) {
  6690. layer.disable();
  6691. }
  6692. for (const editor of this.#allEditors.values()) {
  6693. editor.disable();
  6694. }
  6695. }
  6696. }
  6697. getEditors(pageIndex) {
  6698. const editors = [];
  6699. for (const editor of this.#allEditors.values()) {
  6700. if (editor.pageIndex === pageIndex) {
  6701. editors.push(editor);
  6702. }
  6703. }
  6704. return editors;
  6705. }
  6706. getEditor(id) {
  6707. return this.#allEditors.get(id);
  6708. }
  6709. addEditor(editor) {
  6710. this.#allEditors.set(editor.id, editor);
  6711. }
  6712. removeEditor(editor) {
  6713. if (editor.div.contains(document.activeElement)) {
  6714. if (this.#focusMainContainerTimeoutId) {
  6715. clearTimeout(this.#focusMainContainerTimeoutId);
  6716. }
  6717. this.#focusMainContainerTimeoutId = setTimeout(() => {
  6718. this.focusMainContainer();
  6719. this.#focusMainContainerTimeoutId = null;
  6720. }, 0);
  6721. }
  6722. this.#allEditors.delete(editor.id);
  6723. this.unselect(editor);
  6724. if (!editor.annotationElementId || !this.#deletedAnnotationsElementIds.has(editor.annotationElementId)) {
  6725. this.#annotationStorage?.remove(editor.id);
  6726. }
  6727. }
  6728. addDeletedAnnotationElement(editor) {
  6729. this.#deletedAnnotationsElementIds.add(editor.annotationElementId);
  6730. this.addChangedExistingAnnotation(editor);
  6731. editor.deleted = true;
  6732. }
  6733. isDeletedAnnotationElement(annotationElementId) {
  6734. return this.#deletedAnnotationsElementIds.has(annotationElementId);
  6735. }
  6736. removeDeletedAnnotationElement(editor) {
  6737. this.#deletedAnnotationsElementIds.delete(editor.annotationElementId);
  6738. this.removeChangedExistingAnnotation(editor);
  6739. editor.deleted = false;
  6740. }
  6741. #addEditorToLayer(editor) {
  6742. const layer = this.#allLayers.get(editor.pageIndex);
  6743. if (layer) {
  6744. layer.addOrRebuild(editor);
  6745. } else {
  6746. this.addEditor(editor);
  6747. this.addToAnnotationStorage(editor);
  6748. }
  6749. }
  6750. setActiveEditor(editor) {
  6751. if (this.#activeEditor === editor) {
  6752. return;
  6753. }
  6754. this.#activeEditor = editor;
  6755. if (editor) {
  6756. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  6757. }
  6758. }
  6759. get #lastSelectedEditor() {
  6760. let ed = null;
  6761. for (ed of this.#selectedEditors) {}
  6762. return ed;
  6763. }
  6764. updateUI(editor) {
  6765. if (this.#lastSelectedEditor === editor) {
  6766. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  6767. }
  6768. }
  6769. toggleSelected(editor) {
  6770. if (this.#selectedEditors.has(editor)) {
  6771. this.#selectedEditors.delete(editor);
  6772. editor.unselect();
  6773. this.#dispatchUpdateStates({
  6774. hasSelectedEditor: this.hasSelection
  6775. });
  6776. return;
  6777. }
  6778. this.#selectedEditors.add(editor);
  6779. editor.select();
  6780. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  6781. this.#dispatchUpdateStates({
  6782. hasSelectedEditor: true
  6783. });
  6784. }
  6785. setSelected(editor) {
  6786. for (const ed of this.#selectedEditors) {
  6787. if (ed !== editor) {
  6788. ed.unselect();
  6789. }
  6790. }
  6791. this.#selectedEditors.clear();
  6792. this.#selectedEditors.add(editor);
  6793. editor.select();
  6794. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  6795. this.#dispatchUpdateStates({
  6796. hasSelectedEditor: true
  6797. });
  6798. }
  6799. isSelected(editor) {
  6800. return this.#selectedEditors.has(editor);
  6801. }
  6802. get firstSelectedEditor() {
  6803. return this.#selectedEditors.values().next().value;
  6804. }
  6805. unselect(editor) {
  6806. editor.unselect();
  6807. this.#selectedEditors.delete(editor);
  6808. this.#dispatchUpdateStates({
  6809. hasSelectedEditor: this.hasSelection
  6810. });
  6811. }
  6812. get hasSelection() {
  6813. return this.#selectedEditors.size !== 0;
  6814. }
  6815. get isEnterHandled() {
  6816. return this.#selectedEditors.size === 1 && this.firstSelectedEditor.isEnterHandled;
  6817. }
  6818. undo() {
  6819. this.#commandManager.undo();
  6820. this.#dispatchUpdateStates({
  6821. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  6822. hasSomethingToRedo: true,
  6823. isEmpty: this.#isEmpty()
  6824. });
  6825. }
  6826. redo() {
  6827. this.#commandManager.redo();
  6828. this.#dispatchUpdateStates({
  6829. hasSomethingToUndo: true,
  6830. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  6831. isEmpty: this.#isEmpty()
  6832. });
  6833. }
  6834. addCommands(params) {
  6835. this.#commandManager.add(params);
  6836. this.#dispatchUpdateStates({
  6837. hasSomethingToUndo: true,
  6838. hasSomethingToRedo: false,
  6839. isEmpty: this.#isEmpty()
  6840. });
  6841. }
  6842. #isEmpty() {
  6843. if (this.#allEditors.size === 0) {
  6844. return true;
  6845. }
  6846. if (this.#allEditors.size === 1) {
  6847. for (const editor of this.#allEditors.values()) {
  6848. return editor.isEmpty();
  6849. }
  6850. }
  6851. return false;
  6852. }
  6853. delete() {
  6854. this.commitOrRemove();
  6855. if (!this.hasSelection) {
  6856. return;
  6857. }
  6858. const editors = [...this.#selectedEditors];
  6859. const cmd = () => {
  6860. for (const editor of editors) {
  6861. editor.remove();
  6862. }
  6863. };
  6864. const undo = () => {
  6865. for (const editor of editors) {
  6866. this.#addEditorToLayer(editor);
  6867. }
  6868. };
  6869. this.addCommands({
  6870. cmd,
  6871. undo,
  6872. mustExec: true
  6873. });
  6874. }
  6875. commitOrRemove() {
  6876. this.#activeEditor?.commitOrRemove();
  6877. }
  6878. hasSomethingToControl() {
  6879. return this.#activeEditor || this.hasSelection;
  6880. }
  6881. #selectEditors(editors) {
  6882. for (const editor of this.#selectedEditors) {
  6883. editor.unselect();
  6884. }
  6885. this.#selectedEditors.clear();
  6886. for (const editor of editors) {
  6887. if (editor.isEmpty()) {
  6888. continue;
  6889. }
  6890. this.#selectedEditors.add(editor);
  6891. editor.select();
  6892. }
  6893. this.#dispatchUpdateStates({
  6894. hasSelectedEditor: this.hasSelection
  6895. });
  6896. }
  6897. selectAll() {
  6898. for (const editor of this.#selectedEditors) {
  6899. editor.commit();
  6900. }
  6901. this.#selectEditors(this.#allEditors.values());
  6902. }
  6903. unselectAll() {
  6904. if (this.#activeEditor) {
  6905. this.#activeEditor.commitOrRemove();
  6906. if (this.#mode !== AnnotationEditorType.NONE) {
  6907. return;
  6908. }
  6909. }
  6910. if (!this.hasSelection) {
  6911. return;
  6912. }
  6913. for (const editor of this.#selectedEditors) {
  6914. editor.unselect();
  6915. }
  6916. this.#selectedEditors.clear();
  6917. this.#dispatchUpdateStates({
  6918. hasSelectedEditor: false
  6919. });
  6920. }
  6921. translateSelectedEditors(x, y, noCommit = false) {
  6922. if (!noCommit) {
  6923. this.commitOrRemove();
  6924. }
  6925. if (!this.hasSelection) {
  6926. return;
  6927. }
  6928. this.#translation[0] += x;
  6929. this.#translation[1] += y;
  6930. const [totalX, totalY] = this.#translation;
  6931. const editors = [...this.#selectedEditors];
  6932. const TIME_TO_WAIT = 1000;
  6933. if (this.#translationTimeoutId) {
  6934. clearTimeout(this.#translationTimeoutId);
  6935. }
  6936. this.#translationTimeoutId = setTimeout(() => {
  6937. this.#translationTimeoutId = null;
  6938. this.#translation[0] = this.#translation[1] = 0;
  6939. this.addCommands({
  6940. cmd: () => {
  6941. for (const editor of editors) {
  6942. if (this.#allEditors.has(editor.id)) {
  6943. editor.translateInPage(totalX, totalY);
  6944. }
  6945. }
  6946. },
  6947. undo: () => {
  6948. for (const editor of editors) {
  6949. if (this.#allEditors.has(editor.id)) {
  6950. editor.translateInPage(-totalX, -totalY);
  6951. }
  6952. }
  6953. },
  6954. mustExec: false
  6955. });
  6956. }, TIME_TO_WAIT);
  6957. for (const editor of editors) {
  6958. editor.translateInPage(x, y);
  6959. }
  6960. }
  6961. setUpDragSession() {
  6962. if (!this.hasSelection) {
  6963. return;
  6964. }
  6965. this.disableUserSelect(true);
  6966. this.#draggingEditors = new Map();
  6967. for (const editor of this.#selectedEditors) {
  6968. this.#draggingEditors.set(editor, {
  6969. savedX: editor.x,
  6970. savedY: editor.y,
  6971. savedPageIndex: editor.pageIndex,
  6972. newX: 0,
  6973. newY: 0,
  6974. newPageIndex: -1
  6975. });
  6976. }
  6977. }
  6978. endDragSession() {
  6979. if (!this.#draggingEditors) {
  6980. return false;
  6981. }
  6982. this.disableUserSelect(false);
  6983. const map = this.#draggingEditors;
  6984. this.#draggingEditors = null;
  6985. let mustBeAddedInUndoStack = false;
  6986. for (const [{
  6987. x,
  6988. y,
  6989. pageIndex
  6990. }, value] of map) {
  6991. value.newX = x;
  6992. value.newY = y;
  6993. value.newPageIndex = pageIndex;
  6994. mustBeAddedInUndoStack ||= x !== value.savedX || y !== value.savedY || pageIndex !== value.savedPageIndex;
  6995. }
  6996. if (!mustBeAddedInUndoStack) {
  6997. return false;
  6998. }
  6999. const move = (editor, x, y, pageIndex) => {
  7000. if (this.#allEditors.has(editor.id)) {
  7001. const parent = this.#allLayers.get(pageIndex);
  7002. if (parent) {
  7003. editor._setParentAndPosition(parent, x, y);
  7004. } else {
  7005. editor.pageIndex = pageIndex;
  7006. editor.x = x;
  7007. editor.y = y;
  7008. }
  7009. }
  7010. };
  7011. this.addCommands({
  7012. cmd: () => {
  7013. for (const [editor, {
  7014. newX,
  7015. newY,
  7016. newPageIndex
  7017. }] of map) {
  7018. move(editor, newX, newY, newPageIndex);
  7019. }
  7020. },
  7021. undo: () => {
  7022. for (const [editor, {
  7023. savedX,
  7024. savedY,
  7025. savedPageIndex
  7026. }] of map) {
  7027. move(editor, savedX, savedY, savedPageIndex);
  7028. }
  7029. },
  7030. mustExec: true
  7031. });
  7032. return true;
  7033. }
  7034. dragSelectedEditors(tx, ty) {
  7035. if (!this.#draggingEditors) {
  7036. return;
  7037. }
  7038. for (const editor of this.#draggingEditors.keys()) {
  7039. editor.drag(tx, ty);
  7040. }
  7041. }
  7042. rebuild(editor) {
  7043. if (editor.parent === null) {
  7044. const parent = this.getLayer(editor.pageIndex);
  7045. if (parent) {
  7046. parent.changeParent(editor);
  7047. parent.addOrRebuild(editor);
  7048. } else {
  7049. this.addEditor(editor);
  7050. this.addToAnnotationStorage(editor);
  7051. editor.rebuild();
  7052. }
  7053. } else {
  7054. editor.parent.addOrRebuild(editor);
  7055. }
  7056. }
  7057. get isEditorHandlingKeyboard() {
  7058. return this.getActive()?.shouldGetKeyboardEvents() || this.#selectedEditors.size === 1 && this.firstSelectedEditor.shouldGetKeyboardEvents();
  7059. }
  7060. isActive(editor) {
  7061. return this.#activeEditor === editor;
  7062. }
  7063. getActive() {
  7064. return this.#activeEditor;
  7065. }
  7066. getMode() {
  7067. return this.#mode;
  7068. }
  7069. get imageManager() {
  7070. return shadow(this, "imageManager", new ImageManager());
  7071. }
  7072. getSelectionBoxes(textLayer) {
  7073. if (!textLayer) {
  7074. return null;
  7075. }
  7076. const selection = document.getSelection();
  7077. for (let i = 0, ii = selection.rangeCount; i < ii; i++) {
  7078. if (!textLayer.contains(selection.getRangeAt(i).commonAncestorContainer)) {
  7079. return null;
  7080. }
  7081. }
  7082. const {
  7083. x: layerX,
  7084. y: layerY,
  7085. width: parentWidth,
  7086. height: parentHeight
  7087. } = textLayer.getBoundingClientRect();
  7088. let rotator;
  7089. switch (textLayer.getAttribute("data-main-rotation")) {
  7090. case "90":
  7091. rotator = (x, y, w, h) => ({
  7092. x: (y - layerY) / parentHeight,
  7093. y: 1 - (x + w - layerX) / parentWidth,
  7094. width: h / parentHeight,
  7095. height: w / parentWidth
  7096. });
  7097. break;
  7098. case "180":
  7099. rotator = (x, y, w, h) => ({
  7100. x: 1 - (x + w - layerX) / parentWidth,
  7101. y: 1 - (y + h - layerY) / parentHeight,
  7102. width: w / parentWidth,
  7103. height: h / parentHeight
  7104. });
  7105. break;
  7106. case "270":
  7107. rotator = (x, y, w, h) => ({
  7108. x: 1 - (y + h - layerY) / parentHeight,
  7109. y: (x - layerX) / parentWidth,
  7110. width: h / parentHeight,
  7111. height: w / parentWidth
  7112. });
  7113. break;
  7114. default:
  7115. rotator = (x, y, w, h) => ({
  7116. x: (x - layerX) / parentWidth,
  7117. y: (y - layerY) / parentHeight,
  7118. width: w / parentWidth,
  7119. height: h / parentHeight
  7120. });
  7121. break;
  7122. }
  7123. const boxes = [];
  7124. for (let i = 0, ii = selection.rangeCount; i < ii; i++) {
  7125. const range = selection.getRangeAt(i);
  7126. if (range.collapsed) {
  7127. continue;
  7128. }
  7129. for (const {
  7130. x,
  7131. y,
  7132. width,
  7133. height
  7134. } of range.getClientRects()) {
  7135. if (width === 0 || height === 0) {
  7136. continue;
  7137. }
  7138. boxes.push(rotator(x, y, width, height));
  7139. }
  7140. }
  7141. return boxes.length === 0 ? null : boxes;
  7142. }
  7143. addChangedExistingAnnotation({
  7144. annotationElementId,
  7145. id
  7146. }) {
  7147. (this.#changedExistingAnnotations ||= new Map()).set(annotationElementId, id);
  7148. }
  7149. removeChangedExistingAnnotation({
  7150. annotationElementId
  7151. }) {
  7152. this.#changedExistingAnnotations?.delete(annotationElementId);
  7153. }
  7154. renderAnnotationElement(annotation) {
  7155. const editorId = this.#changedExistingAnnotations?.get(annotation.data.id);
  7156. if (!editorId) {
  7157. return;
  7158. }
  7159. const editor = this.#annotationStorage.getRawValue(editorId);
  7160. if (!editor) {
  7161. return;
  7162. }
  7163. if (this.#mode === AnnotationEditorType.NONE && !editor.hasBeenModified) {
  7164. return;
  7165. }
  7166. editor.renderAnnotationElement(annotation);
  7167. }
  7168. }
  7169. ;// ./src/display/editor/alt_text.js
  7170. class AltText {
  7171. #altText = null;
  7172. #altTextDecorative = false;
  7173. #altTextButton = null;
  7174. #altTextTooltip = null;
  7175. #altTextTooltipTimeout = null;
  7176. #altTextWasFromKeyBoard = false;
  7177. #badge = null;
  7178. #editor = null;
  7179. #guessedText = null;
  7180. #textWithDisclaimer = null;
  7181. #useNewAltTextFlow = false;
  7182. static #l10nNewButton = null;
  7183. static _l10nPromise = null;
  7184. constructor(editor) {
  7185. this.#editor = editor;
  7186. this.#useNewAltTextFlow = editor._uiManager.useNewAltTextFlow;
  7187. AltText.#l10nNewButton ||= Object.freeze({
  7188. added: "pdfjs-editor-new-alt-text-added-button-label",
  7189. missing: "pdfjs-editor-new-alt-text-missing-button-label",
  7190. review: "pdfjs-editor-new-alt-text-to-review-button-label"
  7191. });
  7192. }
  7193. static initialize(l10nPromise) {
  7194. AltText._l10nPromise ||= l10nPromise;
  7195. }
  7196. async render() {
  7197. const altText = this.#altTextButton = document.createElement("button");
  7198. altText.className = "altText";
  7199. let msg;
  7200. if (this.#useNewAltTextFlow) {
  7201. altText.classList.add("new");
  7202. msg = await AltText._l10nPromise.get(AltText.#l10nNewButton.missing);
  7203. } else {
  7204. msg = await AltText._l10nPromise.get("pdfjs-editor-alt-text-button-label");
  7205. }
  7206. altText.textContent = msg;
  7207. altText.setAttribute("aria-label", msg);
  7208. altText.tabIndex = "0";
  7209. const signal = this.#editor._uiManager._signal;
  7210. altText.addEventListener("contextmenu", noContextMenu, {
  7211. signal
  7212. });
  7213. altText.addEventListener("pointerdown", event => event.stopPropagation(), {
  7214. signal
  7215. });
  7216. const onClick = event => {
  7217. event.preventDefault();
  7218. this.#editor._uiManager.editAltText(this.#editor);
  7219. if (this.#useNewAltTextFlow) {
  7220. this.#editor._reportTelemetry({
  7221. action: "pdfjs.image.alt_text.image_status_label_clicked",
  7222. data: {
  7223. label: this.#label
  7224. }
  7225. });
  7226. }
  7227. };
  7228. altText.addEventListener("click", onClick, {
  7229. capture: true,
  7230. signal
  7231. });
  7232. altText.addEventListener("keydown", event => {
  7233. if (event.target === altText && event.key === "Enter") {
  7234. this.#altTextWasFromKeyBoard = true;
  7235. onClick(event);
  7236. }
  7237. }, {
  7238. signal
  7239. });
  7240. await this.#setState();
  7241. return altText;
  7242. }
  7243. get #label() {
  7244. return this.#altText && "added" || this.#altText === null && this.guessedText && "review" || "missing";
  7245. }
  7246. finish() {
  7247. if (!this.#altTextButton) {
  7248. return;
  7249. }
  7250. this.#altTextButton.focus({
  7251. focusVisible: this.#altTextWasFromKeyBoard
  7252. });
  7253. this.#altTextWasFromKeyBoard = false;
  7254. }
  7255. isEmpty() {
  7256. if (this.#useNewAltTextFlow) {
  7257. return this.#altText === null;
  7258. }
  7259. return !this.#altText && !this.#altTextDecorative;
  7260. }
  7261. hasData() {
  7262. if (this.#useNewAltTextFlow) {
  7263. return this.#altText !== null || !!this.#guessedText;
  7264. }
  7265. return this.isEmpty();
  7266. }
  7267. get guessedText() {
  7268. return this.#guessedText;
  7269. }
  7270. async setGuessedText(guessedText) {
  7271. if (this.#altText !== null) {
  7272. return;
  7273. }
  7274. this.#guessedText = guessedText;
  7275. this.#textWithDisclaimer = await AltText._l10nPromise.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer")({
  7276. generatedAltText: guessedText
  7277. });
  7278. this.#setState();
  7279. }
  7280. toggleAltTextBadge(visibility = false) {
  7281. if (!this.#useNewAltTextFlow || this.#altText) {
  7282. this.#badge?.remove();
  7283. this.#badge = null;
  7284. return;
  7285. }
  7286. if (!this.#badge) {
  7287. const badge = this.#badge = document.createElement("div");
  7288. badge.className = "noAltTextBadge";
  7289. this.#editor.div.append(badge);
  7290. }
  7291. this.#badge.classList.toggle("hidden", !visibility);
  7292. }
  7293. serialize(isForCopying) {
  7294. let altText = this.#altText;
  7295. if (!isForCopying && this.#guessedText === altText) {
  7296. altText = this.#textWithDisclaimer;
  7297. }
  7298. return {
  7299. altText,
  7300. decorative: this.#altTextDecorative,
  7301. guessedText: this.#guessedText,
  7302. textWithDisclaimer: this.#textWithDisclaimer
  7303. };
  7304. }
  7305. get data() {
  7306. return {
  7307. altText: this.#altText,
  7308. decorative: this.#altTextDecorative
  7309. };
  7310. }
  7311. set data({
  7312. altText,
  7313. decorative,
  7314. guessedText,
  7315. textWithDisclaimer,
  7316. cancel = false
  7317. }) {
  7318. if (guessedText) {
  7319. this.#guessedText = guessedText;
  7320. this.#textWithDisclaimer = textWithDisclaimer;
  7321. }
  7322. if (this.#altText === altText && this.#altTextDecorative === decorative) {
  7323. return;
  7324. }
  7325. if (!cancel) {
  7326. this.#altText = altText;
  7327. this.#altTextDecorative = decorative;
  7328. }
  7329. this.#setState();
  7330. }
  7331. toggle(enabled = false) {
  7332. if (!this.#altTextButton) {
  7333. return;
  7334. }
  7335. if (!enabled && this.#altTextTooltipTimeout) {
  7336. clearTimeout(this.#altTextTooltipTimeout);
  7337. this.#altTextTooltipTimeout = null;
  7338. }
  7339. this.#altTextButton.disabled = !enabled;
  7340. }
  7341. shown() {
  7342. this.#editor._reportTelemetry({
  7343. action: "pdfjs.image.alt_text.image_status_label_displayed",
  7344. data: {
  7345. label: this.#label
  7346. }
  7347. });
  7348. }
  7349. destroy() {
  7350. this.#altTextButton?.remove();
  7351. this.#altTextButton = null;
  7352. this.#altTextTooltip = null;
  7353. this.#badge?.remove();
  7354. this.#badge = null;
  7355. }
  7356. async #setState() {
  7357. const button = this.#altTextButton;
  7358. if (!button) {
  7359. return;
  7360. }
  7361. if (this.#useNewAltTextFlow) {
  7362. button.classList.toggle("done", !!this.#altText);
  7363. AltText._l10nPromise.get(AltText.#l10nNewButton[this.#label]).then(msg => {
  7364. button.setAttribute("aria-label", msg);
  7365. for (const child of button.childNodes) {
  7366. if (child.nodeType === Node.TEXT_NODE) {
  7367. child.textContent = msg;
  7368. break;
  7369. }
  7370. }
  7371. });
  7372. if (!this.#altText) {
  7373. this.#altTextTooltip?.remove();
  7374. return;
  7375. }
  7376. } else {
  7377. if (!this.#altText && !this.#altTextDecorative) {
  7378. button.classList.remove("done");
  7379. this.#altTextTooltip?.remove();
  7380. return;
  7381. }
  7382. button.classList.add("done");
  7383. AltText._l10nPromise.get("pdfjs-editor-alt-text-edit-button-label").then(msg => {
  7384. button.setAttribute("aria-label", msg);
  7385. });
  7386. }
  7387. let tooltip = this.#altTextTooltip;
  7388. if (!tooltip) {
  7389. this.#altTextTooltip = tooltip = document.createElement("span");
  7390. tooltip.className = "tooltip";
  7391. tooltip.setAttribute("role", "tooltip");
  7392. tooltip.id = `alt-text-tooltip-${this.#editor.id}`;
  7393. const DELAY_TO_SHOW_TOOLTIP = 100;
  7394. const signal = this.#editor._uiManager._signal;
  7395. signal.addEventListener("abort", () => {
  7396. clearTimeout(this.#altTextTooltipTimeout);
  7397. this.#altTextTooltipTimeout = null;
  7398. }, {
  7399. once: true
  7400. });
  7401. button.addEventListener("mouseenter", () => {
  7402. this.#altTextTooltipTimeout = setTimeout(() => {
  7403. this.#altTextTooltipTimeout = null;
  7404. this.#altTextTooltip.classList.add("show");
  7405. this.#editor._reportTelemetry({
  7406. action: "alt_text_tooltip"
  7407. });
  7408. }, DELAY_TO_SHOW_TOOLTIP);
  7409. }, {
  7410. signal
  7411. });
  7412. button.addEventListener("mouseleave", () => {
  7413. if (this.#altTextTooltipTimeout) {
  7414. clearTimeout(this.#altTextTooltipTimeout);
  7415. this.#altTextTooltipTimeout = null;
  7416. }
  7417. this.#altTextTooltip?.classList.remove("show");
  7418. }, {
  7419. signal
  7420. });
  7421. }
  7422. tooltip.innerText = this.#altTextDecorative ? await AltText._l10nPromise.get("pdfjs-editor-alt-text-decorative-tooltip") : this.#altText;
  7423. if (!tooltip.parentNode) {
  7424. button.append(tooltip);
  7425. }
  7426. const element = this.#editor.getImageForAltText();
  7427. element?.setAttribute("aria-describedby", tooltip.id);
  7428. }
  7429. }
  7430. ;// ./src/display/editor/editor.js
  7431. class AnnotationEditor {
  7432. #accessibilityData = null;
  7433. #allResizerDivs = null;
  7434. #altText = null;
  7435. #disabled = false;
  7436. #keepAspectRatio = false;
  7437. #resizersDiv = null;
  7438. #savedDimensions = null;
  7439. #focusAC = null;
  7440. #focusedResizerName = "";
  7441. #hasBeenClicked = false;
  7442. #initialPosition = null;
  7443. #isEditing = false;
  7444. #isInEditMode = false;
  7445. #isResizerEnabledForKeyboard = false;
  7446. #moveInDOMTimeout = null;
  7447. #prevDragX = 0;
  7448. #prevDragY = 0;
  7449. #telemetryTimeouts = null;
  7450. _editToolbar = null;
  7451. _initialOptions = Object.create(null);
  7452. _initialData = null;
  7453. _isVisible = true;
  7454. _uiManager = null;
  7455. _focusEventsAllowed = true;
  7456. static _l10nPromise = null;
  7457. static _l10nResizer = null;
  7458. #isDraggable = false;
  7459. #zIndex = AnnotationEditor._zIndex++;
  7460. static _borderLineWidth = -1;
  7461. static _colorManager = new ColorManager();
  7462. static _zIndex = 1;
  7463. static _telemetryTimeout = 1000;
  7464. static get _resizerKeyboardManager() {
  7465. const resize = AnnotationEditor.prototype._resizeWithKeyboard;
  7466. const small = AnnotationEditorUIManager.TRANSLATE_SMALL;
  7467. const big = AnnotationEditorUIManager.TRANSLATE_BIG;
  7468. return shadow(this, "_resizerKeyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], resize, {
  7469. args: [-small, 0]
  7470. }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], resize, {
  7471. args: [-big, 0]
  7472. }], [["ArrowRight", "mac+ArrowRight"], resize, {
  7473. args: [small, 0]
  7474. }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], resize, {
  7475. args: [big, 0]
  7476. }], [["ArrowUp", "mac+ArrowUp"], resize, {
  7477. args: [0, -small]
  7478. }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], resize, {
  7479. args: [0, -big]
  7480. }], [["ArrowDown", "mac+ArrowDown"], resize, {
  7481. args: [0, small]
  7482. }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], resize, {
  7483. args: [0, big]
  7484. }], [["Escape", "mac+Escape"], AnnotationEditor.prototype._stopResizingWithKeyboard]]));
  7485. }
  7486. constructor(parameters) {
  7487. this.parent = parameters.parent;
  7488. this.id = parameters.id;
  7489. this.width = this.height = null;
  7490. this.pageIndex = parameters.parent.pageIndex;
  7491. this.name = parameters.name;
  7492. this.div = null;
  7493. this._uiManager = parameters.uiManager;
  7494. this.annotationElementId = null;
  7495. this._willKeepAspectRatio = false;
  7496. this._initialOptions.isCentered = parameters.isCentered;
  7497. this._structTreeParentId = null;
  7498. const {
  7499. rotation,
  7500. rawDims: {
  7501. pageWidth,
  7502. pageHeight,
  7503. pageX,
  7504. pageY
  7505. }
  7506. } = this.parent.viewport;
  7507. this.rotation = rotation;
  7508. this.pageRotation = (360 + rotation - this._uiManager.viewParameters.rotation) % 360;
  7509. this.pageDimensions = [pageWidth, pageHeight];
  7510. this.pageTranslation = [pageX, pageY];
  7511. const [width, height] = this.parentDimensions;
  7512. this.x = parameters.x / width;
  7513. this.y = parameters.y / height;
  7514. this.isAttachedToDOM = false;
  7515. this.deleted = false;
  7516. }
  7517. get editorType() {
  7518. return Object.getPrototypeOf(this).constructor._type;
  7519. }
  7520. static get _defaultLineColor() {
  7521. return shadow(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText"));
  7522. }
  7523. static deleteAnnotationElement(editor) {
  7524. const fakeEditor = new FakeEditor({
  7525. id: editor.parent.getNextId(),
  7526. parent: editor.parent,
  7527. uiManager: editor._uiManager
  7528. });
  7529. fakeEditor.annotationElementId = editor.annotationElementId;
  7530. fakeEditor.deleted = true;
  7531. fakeEditor._uiManager.addToAnnotationStorage(fakeEditor);
  7532. }
  7533. static initialize(l10n, _uiManager, options) {
  7534. AnnotationEditor._l10nResizer ||= Object.freeze({
  7535. topLeft: "pdfjs-editor-resizer-top-left",
  7536. topMiddle: "pdfjs-editor-resizer-top-middle",
  7537. topRight: "pdfjs-editor-resizer-top-right",
  7538. middleRight: "pdfjs-editor-resizer-middle-right",
  7539. bottomRight: "pdfjs-editor-resizer-bottom-right",
  7540. bottomMiddle: "pdfjs-editor-resizer-bottom-middle",
  7541. bottomLeft: "pdfjs-editor-resizer-bottom-left",
  7542. middleLeft: "pdfjs-editor-resizer-middle-left"
  7543. });
  7544. AnnotationEditor._l10nPromise ||= new Map([...["pdfjs-editor-alt-text-button-label", "pdfjs-editor-alt-text-edit-button-label", "pdfjs-editor-alt-text-decorative-tooltip", "pdfjs-editor-new-alt-text-added-button-label", "pdfjs-editor-new-alt-text-missing-button-label", "pdfjs-editor-new-alt-text-to-review-button-label"].map(str => [str, l10n.get(str)]), ...["pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer"].map(str => [str, l10n.get.bind(l10n, str)])]);
  7545. if (options?.strings) {
  7546. for (const str of options.strings) {
  7547. AnnotationEditor._l10nPromise.set(str, l10n.get(str));
  7548. }
  7549. }
  7550. if (AnnotationEditor._borderLineWidth !== -1) {
  7551. return;
  7552. }
  7553. const style = getComputedStyle(document.documentElement);
  7554. AnnotationEditor._borderLineWidth = parseFloat(style.getPropertyValue("--outline-width")) || 0;
  7555. }
  7556. static updateDefaultParams(_type, _value) {}
  7557. static get defaultPropertiesToUpdate() {
  7558. return [];
  7559. }
  7560. static isHandlingMimeForPasting(mime) {
  7561. return false;
  7562. }
  7563. static paste(item, parent) {
  7564. unreachable("Not implemented");
  7565. }
  7566. get propertiesToUpdate() {
  7567. return [];
  7568. }
  7569. get _isDraggable() {
  7570. return this.#isDraggable;
  7571. }
  7572. set _isDraggable(value) {
  7573. this.#isDraggable = value;
  7574. this.div?.classList.toggle("draggable", value);
  7575. }
  7576. get isEnterHandled() {
  7577. return true;
  7578. }
  7579. center() {
  7580. const [pageWidth, pageHeight] = this.pageDimensions;
  7581. switch (this.parentRotation) {
  7582. case 90:
  7583. this.x -= this.height * pageHeight / (pageWidth * 2);
  7584. this.y += this.width * pageWidth / (pageHeight * 2);
  7585. break;
  7586. case 180:
  7587. this.x += this.width / 2;
  7588. this.y += this.height / 2;
  7589. break;
  7590. case 270:
  7591. this.x += this.height * pageHeight / (pageWidth * 2);
  7592. this.y -= this.width * pageWidth / (pageHeight * 2);
  7593. break;
  7594. default:
  7595. this.x -= this.width / 2;
  7596. this.y -= this.height / 2;
  7597. break;
  7598. }
  7599. this.fixAndSetPosition();
  7600. }
  7601. addCommands(params) {
  7602. this._uiManager.addCommands(params);
  7603. }
  7604. get currentLayer() {
  7605. return this._uiManager.currentLayer;
  7606. }
  7607. setInBackground() {
  7608. this.div.style.zIndex = 0;
  7609. }
  7610. setInForeground() {
  7611. this.div.style.zIndex = this.#zIndex;
  7612. }
  7613. setParent(parent) {
  7614. if (parent !== null) {
  7615. this.pageIndex = parent.pageIndex;
  7616. this.pageDimensions = parent.pageDimensions;
  7617. } else {
  7618. this.#stopResizing();
  7619. }
  7620. this.parent = parent;
  7621. }
  7622. focusin(event) {
  7623. if (!this._focusEventsAllowed) {
  7624. return;
  7625. }
  7626. if (!this.#hasBeenClicked) {
  7627. this.parent.setSelected(this);
  7628. } else {
  7629. this.#hasBeenClicked = false;
  7630. }
  7631. }
  7632. focusout(event) {
  7633. if (!this._focusEventsAllowed) {
  7634. return;
  7635. }
  7636. if (!this.isAttachedToDOM) {
  7637. return;
  7638. }
  7639. const target = event.relatedTarget;
  7640. if (target?.closest(`#${this.id}`)) {
  7641. return;
  7642. }
  7643. event.preventDefault();
  7644. if (!this.parent?.isMultipleSelection) {
  7645. this.commitOrRemove();
  7646. }
  7647. }
  7648. commitOrRemove() {
  7649. if (this.isEmpty()) {
  7650. this.remove();
  7651. } else {
  7652. this.commit();
  7653. }
  7654. }
  7655. commit() {
  7656. this.addToAnnotationStorage();
  7657. }
  7658. addToAnnotationStorage() {
  7659. this._uiManager.addToAnnotationStorage(this);
  7660. }
  7661. setAt(x, y, tx, ty) {
  7662. const [width, height] = this.parentDimensions;
  7663. [tx, ty] = this.screenToPageTranslation(tx, ty);
  7664. this.x = (x + tx) / width;
  7665. this.y = (y + ty) / height;
  7666. this.fixAndSetPosition();
  7667. }
  7668. #translate([width, height], x, y) {
  7669. [x, y] = this.screenToPageTranslation(x, y);
  7670. this.x += x / width;
  7671. this.y += y / height;
  7672. this.fixAndSetPosition();
  7673. }
  7674. translate(x, y) {
  7675. this.#translate(this.parentDimensions, x, y);
  7676. }
  7677. translateInPage(x, y) {
  7678. this.#initialPosition ||= [this.x, this.y];
  7679. this.#translate(this.pageDimensions, x, y);
  7680. this.div.scrollIntoView({
  7681. block: "nearest"
  7682. });
  7683. }
  7684. drag(tx, ty) {
  7685. this.#initialPosition ||= [this.x, this.y];
  7686. const [parentWidth, parentHeight] = this.parentDimensions;
  7687. this.x += tx / parentWidth;
  7688. this.y += ty / parentHeight;
  7689. if (this.parent && (this.x < 0 || this.x > 1 || this.y < 0 || this.y > 1)) {
  7690. const {
  7691. x,
  7692. y
  7693. } = this.div.getBoundingClientRect();
  7694. if (this.parent.findNewParent(this, x, y)) {
  7695. this.x -= Math.floor(this.x);
  7696. this.y -= Math.floor(this.y);
  7697. }
  7698. }
  7699. let {
  7700. x,
  7701. y
  7702. } = this;
  7703. const [bx, by] = this.getBaseTranslation();
  7704. x += bx;
  7705. y += by;
  7706. this.div.style.left = `${(100 * x).toFixed(2)}%`;
  7707. this.div.style.top = `${(100 * y).toFixed(2)}%`;
  7708. this.div.scrollIntoView({
  7709. block: "nearest"
  7710. });
  7711. }
  7712. get _hasBeenMoved() {
  7713. return !!this.#initialPosition && (this.#initialPosition[0] !== this.x || this.#initialPosition[1] !== this.y);
  7714. }
  7715. getBaseTranslation() {
  7716. const [parentWidth, parentHeight] = this.parentDimensions;
  7717. const {
  7718. _borderLineWidth
  7719. } = AnnotationEditor;
  7720. const x = _borderLineWidth / parentWidth;
  7721. const y = _borderLineWidth / parentHeight;
  7722. switch (this.rotation) {
  7723. case 90:
  7724. return [-x, y];
  7725. case 180:
  7726. return [x, y];
  7727. case 270:
  7728. return [x, -y];
  7729. default:
  7730. return [-x, -y];
  7731. }
  7732. }
  7733. get _mustFixPosition() {
  7734. return true;
  7735. }
  7736. fixAndSetPosition(rotation = this.rotation) {
  7737. const [pageWidth, pageHeight] = this.pageDimensions;
  7738. let {
  7739. x,
  7740. y,
  7741. width,
  7742. height
  7743. } = this;
  7744. width *= pageWidth;
  7745. height *= pageHeight;
  7746. x *= pageWidth;
  7747. y *= pageHeight;
  7748. if (this._mustFixPosition) {
  7749. switch (rotation) {
  7750. case 0:
  7751. x = Math.max(0, Math.min(pageWidth - width, x));
  7752. y = Math.max(0, Math.min(pageHeight - height, y));
  7753. break;
  7754. case 90:
  7755. x = Math.max(0, Math.min(pageWidth - height, x));
  7756. y = Math.min(pageHeight, Math.max(width, y));
  7757. break;
  7758. case 180:
  7759. x = Math.min(pageWidth, Math.max(width, x));
  7760. y = Math.min(pageHeight, Math.max(height, y));
  7761. break;
  7762. case 270:
  7763. x = Math.min(pageWidth, Math.max(height, x));
  7764. y = Math.max(0, Math.min(pageHeight - width, y));
  7765. break;
  7766. }
  7767. }
  7768. this.x = x /= pageWidth;
  7769. this.y = y /= pageHeight;
  7770. const [bx, by] = this.getBaseTranslation();
  7771. x += bx;
  7772. y += by;
  7773. const {
  7774. style
  7775. } = this.div;
  7776. style.left = `${(100 * x).toFixed(2)}%`;
  7777. style.top = `${(100 * y).toFixed(2)}%`;
  7778. this.moveInDOM();
  7779. }
  7780. static #rotatePoint(x, y, angle) {
  7781. switch (angle) {
  7782. case 90:
  7783. return [y, -x];
  7784. case 180:
  7785. return [-x, -y];
  7786. case 270:
  7787. return [-y, x];
  7788. default:
  7789. return [x, y];
  7790. }
  7791. }
  7792. screenToPageTranslation(x, y) {
  7793. return AnnotationEditor.#rotatePoint(x, y, this.parentRotation);
  7794. }
  7795. pageTranslationToScreen(x, y) {
  7796. return AnnotationEditor.#rotatePoint(x, y, 360 - this.parentRotation);
  7797. }
  7798. #getRotationMatrix(rotation) {
  7799. switch (rotation) {
  7800. case 90:
  7801. {
  7802. const [pageWidth, pageHeight] = this.pageDimensions;
  7803. return [0, -pageWidth / pageHeight, pageHeight / pageWidth, 0];
  7804. }
  7805. case 180:
  7806. return [-1, 0, 0, -1];
  7807. case 270:
  7808. {
  7809. const [pageWidth, pageHeight] = this.pageDimensions;
  7810. return [0, pageWidth / pageHeight, -pageHeight / pageWidth, 0];
  7811. }
  7812. default:
  7813. return [1, 0, 0, 1];
  7814. }
  7815. }
  7816. get parentScale() {
  7817. return this._uiManager.viewParameters.realScale;
  7818. }
  7819. get parentRotation() {
  7820. return (this._uiManager.viewParameters.rotation + this.pageRotation) % 360;
  7821. }
  7822. get parentDimensions() {
  7823. const {
  7824. parentScale,
  7825. pageDimensions: [pageWidth, pageHeight]
  7826. } = this;
  7827. return [pageWidth * parentScale, pageHeight * parentScale];
  7828. }
  7829. setDims(width, height) {
  7830. const [parentWidth, parentHeight] = this.parentDimensions;
  7831. this.div.style.width = `${(100 * width / parentWidth).toFixed(2)}%`;
  7832. if (!this.#keepAspectRatio) {
  7833. this.div.style.height = `${(100 * height / parentHeight).toFixed(2)}%`;
  7834. }
  7835. }
  7836. fixDims() {
  7837. const {
  7838. style
  7839. } = this.div;
  7840. const {
  7841. height,
  7842. width
  7843. } = style;
  7844. const widthPercent = width.endsWith("%");
  7845. const heightPercent = !this.#keepAspectRatio && height.endsWith("%");
  7846. if (widthPercent && heightPercent) {
  7847. return;
  7848. }
  7849. const [parentWidth, parentHeight] = this.parentDimensions;
  7850. if (!widthPercent) {
  7851. style.width = `${(100 * parseFloat(width) / parentWidth).toFixed(2)}%`;
  7852. }
  7853. if (!this.#keepAspectRatio && !heightPercent) {
  7854. style.height = `${(100 * parseFloat(height) / parentHeight).toFixed(2)}%`;
  7855. }
  7856. }
  7857. getInitialTranslation() {
  7858. return [0, 0];
  7859. }
  7860. #createResizers() {
  7861. if (this.#resizersDiv) {
  7862. return;
  7863. }
  7864. this.#resizersDiv = document.createElement("div");
  7865. this.#resizersDiv.classList.add("resizers");
  7866. const classes = this._willKeepAspectRatio ? ["topLeft", "topRight", "bottomRight", "bottomLeft"] : ["topLeft", "topMiddle", "topRight", "middleRight", "bottomRight", "bottomMiddle", "bottomLeft", "middleLeft"];
  7867. const signal = this._uiManager._signal;
  7868. for (const name of classes) {
  7869. const div = document.createElement("div");
  7870. this.#resizersDiv.append(div);
  7871. div.classList.add("resizer", name);
  7872. div.setAttribute("data-resizer-name", name);
  7873. div.addEventListener("pointerdown", this.#resizerPointerdown.bind(this, name), {
  7874. signal
  7875. });
  7876. div.addEventListener("contextmenu", noContextMenu, {
  7877. signal
  7878. });
  7879. div.tabIndex = -1;
  7880. }
  7881. this.div.prepend(this.#resizersDiv);
  7882. }
  7883. #resizerPointerdown(name, event) {
  7884. event.preventDefault();
  7885. const {
  7886. isMac
  7887. } = util_FeatureTest.platform;
  7888. if (event.button !== 0 || event.ctrlKey && isMac) {
  7889. return;
  7890. }
  7891. this.#altText?.toggle(false);
  7892. const savedDraggable = this._isDraggable;
  7893. this._isDraggable = false;
  7894. const ac = new AbortController();
  7895. const signal = this._uiManager.combinedSignal(ac);
  7896. this.parent.togglePointerEvents(false);
  7897. window.addEventListener("pointermove", this.#resizerPointermove.bind(this, name), {
  7898. passive: true,
  7899. capture: true,
  7900. signal
  7901. });
  7902. window.addEventListener("contextmenu", noContextMenu, {
  7903. signal
  7904. });
  7905. const savedX = this.x;
  7906. const savedY = this.y;
  7907. const savedWidth = this.width;
  7908. const savedHeight = this.height;
  7909. const savedParentCursor = this.parent.div.style.cursor;
  7910. const savedCursor = this.div.style.cursor;
  7911. this.div.style.cursor = this.parent.div.style.cursor = window.getComputedStyle(event.target).cursor;
  7912. const pointerUpCallback = () => {
  7913. ac.abort();
  7914. this.parent.togglePointerEvents(true);
  7915. this.#altText?.toggle(true);
  7916. this._isDraggable = savedDraggable;
  7917. this.parent.div.style.cursor = savedParentCursor;
  7918. this.div.style.cursor = savedCursor;
  7919. this.#addResizeToUndoStack(savedX, savedY, savedWidth, savedHeight);
  7920. };
  7921. window.addEventListener("pointerup", pointerUpCallback, {
  7922. signal
  7923. });
  7924. window.addEventListener("blur", pointerUpCallback, {
  7925. signal
  7926. });
  7927. }
  7928. #addResizeToUndoStack(savedX, savedY, savedWidth, savedHeight) {
  7929. const newX = this.x;
  7930. const newY = this.y;
  7931. const newWidth = this.width;
  7932. const newHeight = this.height;
  7933. if (newX === savedX && newY === savedY && newWidth === savedWidth && newHeight === savedHeight) {
  7934. return;
  7935. }
  7936. this.addCommands({
  7937. cmd: () => {
  7938. this.width = newWidth;
  7939. this.height = newHeight;
  7940. this.x = newX;
  7941. this.y = newY;
  7942. const [parentWidth, parentHeight] = this.parentDimensions;
  7943. this.setDims(parentWidth * newWidth, parentHeight * newHeight);
  7944. this.fixAndSetPosition();
  7945. },
  7946. undo: () => {
  7947. this.width = savedWidth;
  7948. this.height = savedHeight;
  7949. this.x = savedX;
  7950. this.y = savedY;
  7951. const [parentWidth, parentHeight] = this.parentDimensions;
  7952. this.setDims(parentWidth * savedWidth, parentHeight * savedHeight);
  7953. this.fixAndSetPosition();
  7954. },
  7955. mustExec: true
  7956. });
  7957. }
  7958. #resizerPointermove(name, event) {
  7959. const [parentWidth, parentHeight] = this.parentDimensions;
  7960. const savedX = this.x;
  7961. const savedY = this.y;
  7962. const savedWidth = this.width;
  7963. const savedHeight = this.height;
  7964. const minWidth = AnnotationEditor.MIN_SIZE / parentWidth;
  7965. const minHeight = AnnotationEditor.MIN_SIZE / parentHeight;
  7966. const round = x => Math.round(x * 10000) / 10000;
  7967. const rotationMatrix = this.#getRotationMatrix(this.rotation);
  7968. const transf = (x, y) => [rotationMatrix[0] * x + rotationMatrix[2] * y, rotationMatrix[1] * x + rotationMatrix[3] * y];
  7969. const invRotationMatrix = this.#getRotationMatrix(360 - this.rotation);
  7970. const invTransf = (x, y) => [invRotationMatrix[0] * x + invRotationMatrix[2] * y, invRotationMatrix[1] * x + invRotationMatrix[3] * y];
  7971. let getPoint;
  7972. let getOpposite;
  7973. let isDiagonal = false;
  7974. let isHorizontal = false;
  7975. switch (name) {
  7976. case "topLeft":
  7977. isDiagonal = true;
  7978. getPoint = (w, h) => [0, 0];
  7979. getOpposite = (w, h) => [w, h];
  7980. break;
  7981. case "topMiddle":
  7982. getPoint = (w, h) => [w / 2, 0];
  7983. getOpposite = (w, h) => [w / 2, h];
  7984. break;
  7985. case "topRight":
  7986. isDiagonal = true;
  7987. getPoint = (w, h) => [w, 0];
  7988. getOpposite = (w, h) => [0, h];
  7989. break;
  7990. case "middleRight":
  7991. isHorizontal = true;
  7992. getPoint = (w, h) => [w, h / 2];
  7993. getOpposite = (w, h) => [0, h / 2];
  7994. break;
  7995. case "bottomRight":
  7996. isDiagonal = true;
  7997. getPoint = (w, h) => [w, h];
  7998. getOpposite = (w, h) => [0, 0];
  7999. break;
  8000. case "bottomMiddle":
  8001. getPoint = (w, h) => [w / 2, h];
  8002. getOpposite = (w, h) => [w / 2, 0];
  8003. break;
  8004. case "bottomLeft":
  8005. isDiagonal = true;
  8006. getPoint = (w, h) => [0, h];
  8007. getOpposite = (w, h) => [w, 0];
  8008. break;
  8009. case "middleLeft":
  8010. isHorizontal = true;
  8011. getPoint = (w, h) => [0, h / 2];
  8012. getOpposite = (w, h) => [w, h / 2];
  8013. break;
  8014. }
  8015. const point = getPoint(savedWidth, savedHeight);
  8016. const oppositePoint = getOpposite(savedWidth, savedHeight);
  8017. let transfOppositePoint = transf(...oppositePoint);
  8018. const oppositeX = round(savedX + transfOppositePoint[0]);
  8019. const oppositeY = round(savedY + transfOppositePoint[1]);
  8020. let ratioX = 1;
  8021. let ratioY = 1;
  8022. let [deltaX, deltaY] = this.screenToPageTranslation(event.movementX, event.movementY);
  8023. [deltaX, deltaY] = invTransf(deltaX / parentWidth, deltaY / parentHeight);
  8024. if (isDiagonal) {
  8025. const oldDiag = Math.hypot(savedWidth, savedHeight);
  8026. ratioX = ratioY = Math.max(Math.min(Math.hypot(oppositePoint[0] - point[0] - deltaX, oppositePoint[1] - point[1] - deltaY) / oldDiag, 1 / savedWidth, 1 / savedHeight), minWidth / savedWidth, minHeight / savedHeight);
  8027. } else if (isHorizontal) {
  8028. ratioX = Math.max(minWidth, Math.min(1, Math.abs(oppositePoint[0] - point[0] - deltaX))) / savedWidth;
  8029. } else {
  8030. ratioY = Math.max(minHeight, Math.min(1, Math.abs(oppositePoint[1] - point[1] - deltaY))) / savedHeight;
  8031. }
  8032. const newWidth = round(savedWidth * ratioX);
  8033. const newHeight = round(savedHeight * ratioY);
  8034. transfOppositePoint = transf(...getOpposite(newWidth, newHeight));
  8035. const newX = oppositeX - transfOppositePoint[0];
  8036. const newY = oppositeY - transfOppositePoint[1];
  8037. this.width = newWidth;
  8038. this.height = newHeight;
  8039. this.x = newX;
  8040. this.y = newY;
  8041. this.setDims(parentWidth * newWidth, parentHeight * newHeight);
  8042. this.fixAndSetPosition();
  8043. }
  8044. altTextFinish() {
  8045. this.#altText?.finish();
  8046. }
  8047. async addEditToolbar() {
  8048. if (this._editToolbar || this.#isInEditMode) {
  8049. return this._editToolbar;
  8050. }
  8051. this._editToolbar = new EditorToolbar(this);
  8052. this.div.append(this._editToolbar.render());
  8053. if (this.#altText) {
  8054. await this._editToolbar.addAltText(this.#altText);
  8055. }
  8056. return this._editToolbar;
  8057. }
  8058. removeEditToolbar() {
  8059. if (!this._editToolbar) {
  8060. return;
  8061. }
  8062. this._editToolbar.remove();
  8063. this._editToolbar = null;
  8064. this.#altText?.destroy();
  8065. }
  8066. addContainer(container) {
  8067. const editToolbarDiv = this._editToolbar?.div;
  8068. if (editToolbarDiv) {
  8069. editToolbarDiv.before(container);
  8070. } else {
  8071. this.div.append(container);
  8072. }
  8073. }
  8074. getClientDimensions() {
  8075. return this.div.getBoundingClientRect();
  8076. }
  8077. async addAltTextButton() {
  8078. if (this.#altText) {
  8079. return;
  8080. }
  8081. AltText.initialize(AnnotationEditor._l10nPromise);
  8082. this.#altText = new AltText(this);
  8083. if (this.#accessibilityData) {
  8084. this.#altText.data = this.#accessibilityData;
  8085. this.#accessibilityData = null;
  8086. }
  8087. await this.addEditToolbar();
  8088. }
  8089. get altTextData() {
  8090. return this.#altText?.data;
  8091. }
  8092. set altTextData(data) {
  8093. if (!this.#altText) {
  8094. return;
  8095. }
  8096. this.#altText.data = data;
  8097. }
  8098. get guessedAltText() {
  8099. return this.#altText?.guessedText;
  8100. }
  8101. async setGuessedAltText(text) {
  8102. await this.#altText?.setGuessedText(text);
  8103. }
  8104. serializeAltText(isForCopying) {
  8105. return this.#altText?.serialize(isForCopying);
  8106. }
  8107. hasAltText() {
  8108. return !!this.#altText && !this.#altText.isEmpty();
  8109. }
  8110. hasAltTextData() {
  8111. return this.#altText?.hasData() ?? false;
  8112. }
  8113. render() {
  8114. this.div = document.createElement("div");
  8115. this.div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360);
  8116. this.div.className = this.name;
  8117. this.div.setAttribute("id", this.id);
  8118. this.div.tabIndex = this.#disabled ? -1 : 0;
  8119. if (!this._isVisible) {
  8120. this.div.classList.add("hidden");
  8121. }
  8122. this.setInForeground();
  8123. this.#addFocusListeners();
  8124. const [parentWidth, parentHeight] = this.parentDimensions;
  8125. if (this.parentRotation % 180 !== 0) {
  8126. this.div.style.maxWidth = `${(100 * parentHeight / parentWidth).toFixed(2)}%`;
  8127. this.div.style.maxHeight = `${(100 * parentWidth / parentHeight).toFixed(2)}%`;
  8128. }
  8129. const [tx, ty] = this.getInitialTranslation();
  8130. this.translate(tx, ty);
  8131. bindEvents(this, this.div, ["pointerdown"]);
  8132. return this.div;
  8133. }
  8134. pointerdown(event) {
  8135. const {
  8136. isMac
  8137. } = util_FeatureTest.platform;
  8138. if (event.button !== 0 || event.ctrlKey && isMac) {
  8139. event.preventDefault();
  8140. return;
  8141. }
  8142. this.#hasBeenClicked = true;
  8143. if (this._isDraggable) {
  8144. this.#setUpDragSession(event);
  8145. return;
  8146. }
  8147. this.#selectOnPointerEvent(event);
  8148. }
  8149. #selectOnPointerEvent(event) {
  8150. const {
  8151. isMac
  8152. } = util_FeatureTest.platform;
  8153. if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) {
  8154. this.parent.toggleSelected(this);
  8155. } else {
  8156. this.parent.setSelected(this);
  8157. }
  8158. }
  8159. #setUpDragSession(event) {
  8160. const isSelected = this._uiManager.isSelected(this);
  8161. this._uiManager.setUpDragSession();
  8162. const ac = new AbortController();
  8163. const signal = this._uiManager.combinedSignal(ac);
  8164. if (isSelected) {
  8165. this.div.classList.add("moving");
  8166. this.#prevDragX = event.clientX;
  8167. this.#prevDragY = event.clientY;
  8168. const pointerMoveCallback = e => {
  8169. const {
  8170. clientX: x,
  8171. clientY: y
  8172. } = e;
  8173. const [tx, ty] = this.screenToPageTranslation(x - this.#prevDragX, y - this.#prevDragY);
  8174. this.#prevDragX = x;
  8175. this.#prevDragY = y;
  8176. this._uiManager.dragSelectedEditors(tx, ty);
  8177. };
  8178. window.addEventListener("pointermove", pointerMoveCallback, {
  8179. passive: true,
  8180. capture: true,
  8181. signal
  8182. });
  8183. }
  8184. const pointerUpCallback = () => {
  8185. ac.abort();
  8186. if (isSelected) {
  8187. this.div.classList.remove("moving");
  8188. }
  8189. this.#hasBeenClicked = false;
  8190. if (!this._uiManager.endDragSession()) {
  8191. this.#selectOnPointerEvent(event);
  8192. }
  8193. };
  8194. window.addEventListener("pointerup", pointerUpCallback, {
  8195. signal
  8196. });
  8197. window.addEventListener("blur", pointerUpCallback, {
  8198. signal
  8199. });
  8200. }
  8201. moveInDOM() {
  8202. if (this.#moveInDOMTimeout) {
  8203. clearTimeout(this.#moveInDOMTimeout);
  8204. }
  8205. this.#moveInDOMTimeout = setTimeout(() => {
  8206. this.#moveInDOMTimeout = null;
  8207. this.parent?.moveEditorInDOM(this);
  8208. }, 0);
  8209. }
  8210. _setParentAndPosition(parent, x, y) {
  8211. parent.changeParent(this);
  8212. this.x = x;
  8213. this.y = y;
  8214. this.fixAndSetPosition();
  8215. }
  8216. getRect(tx, ty, rotation = this.rotation) {
  8217. const scale = this.parentScale;
  8218. const [pageWidth, pageHeight] = this.pageDimensions;
  8219. const [pageX, pageY] = this.pageTranslation;
  8220. const shiftX = tx / scale;
  8221. const shiftY = ty / scale;
  8222. const x = this.x * pageWidth;
  8223. const y = this.y * pageHeight;
  8224. const width = this.width * pageWidth;
  8225. const height = this.height * pageHeight;
  8226. switch (rotation) {
  8227. case 0:
  8228. return [x + shiftX + pageX, pageHeight - y - shiftY - height + pageY, x + shiftX + width + pageX, pageHeight - y - shiftY + pageY];
  8229. case 90:
  8230. return [x + shiftY + pageX, pageHeight - y + shiftX + pageY, x + shiftY + height + pageX, pageHeight - y + shiftX + width + pageY];
  8231. case 180:
  8232. return [x - shiftX - width + pageX, pageHeight - y + shiftY + pageY, x - shiftX + pageX, pageHeight - y + shiftY + height + pageY];
  8233. case 270:
  8234. return [x - shiftY - height + pageX, pageHeight - y - shiftX - width + pageY, x - shiftY + pageX, pageHeight - y - shiftX + pageY];
  8235. default:
  8236. throw new Error("Invalid rotation");
  8237. }
  8238. }
  8239. getRectInCurrentCoords(rect, pageHeight) {
  8240. const [x1, y1, x2, y2] = rect;
  8241. const width = x2 - x1;
  8242. const height = y2 - y1;
  8243. switch (this.rotation) {
  8244. case 0:
  8245. return [x1, pageHeight - y2, width, height];
  8246. case 90:
  8247. return [x1, pageHeight - y1, height, width];
  8248. case 180:
  8249. return [x2, pageHeight - y1, width, height];
  8250. case 270:
  8251. return [x2, pageHeight - y2, height, width];
  8252. default:
  8253. throw new Error("Invalid rotation");
  8254. }
  8255. }
  8256. onceAdded() {}
  8257. isEmpty() {
  8258. return false;
  8259. }
  8260. enableEditMode() {
  8261. this.#isInEditMode = true;
  8262. }
  8263. disableEditMode() {
  8264. this.#isInEditMode = false;
  8265. }
  8266. isInEditMode() {
  8267. return this.#isInEditMode;
  8268. }
  8269. shouldGetKeyboardEvents() {
  8270. return this.#isResizerEnabledForKeyboard;
  8271. }
  8272. needsToBeRebuilt() {
  8273. return this.div && !this.isAttachedToDOM;
  8274. }
  8275. #addFocusListeners() {
  8276. if (this.#focusAC || !this.div) {
  8277. return;
  8278. }
  8279. this.#focusAC = new AbortController();
  8280. const signal = this._uiManager.combinedSignal(this.#focusAC);
  8281. this.div.addEventListener("focusin", this.focusin.bind(this), {
  8282. signal
  8283. });
  8284. this.div.addEventListener("focusout", this.focusout.bind(this), {
  8285. signal
  8286. });
  8287. }
  8288. rebuild() {
  8289. this.#addFocusListeners();
  8290. }
  8291. rotate(_angle) {}
  8292. serializeDeleted() {
  8293. return {
  8294. id: this.annotationElementId,
  8295. deleted: true,
  8296. pageIndex: this.pageIndex,
  8297. popupRef: this._initialData?.popupRef || ""
  8298. };
  8299. }
  8300. serialize(isForCopying = false, context = null) {
  8301. unreachable("An editor must be serializable");
  8302. }
  8303. static async deserialize(data, parent, uiManager) {
  8304. const editor = new this.prototype.constructor({
  8305. parent,
  8306. id: parent.getNextId(),
  8307. uiManager
  8308. });
  8309. editor.rotation = data.rotation;
  8310. editor.#accessibilityData = data.accessibilityData;
  8311. const [pageWidth, pageHeight] = editor.pageDimensions;
  8312. const [x, y, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight);
  8313. editor.x = x / pageWidth;
  8314. editor.y = y / pageHeight;
  8315. editor.width = width / pageWidth;
  8316. editor.height = height / pageHeight;
  8317. return editor;
  8318. }
  8319. get hasBeenModified() {
  8320. return !!this.annotationElementId && (this.deleted || this.serialize() !== null);
  8321. }
  8322. remove() {
  8323. this.#focusAC?.abort();
  8324. this.#focusAC = null;
  8325. if (!this.isEmpty()) {
  8326. this.commit();
  8327. }
  8328. if (this.parent) {
  8329. this.parent.remove(this);
  8330. } else {
  8331. this._uiManager.removeEditor(this);
  8332. }
  8333. if (this.#moveInDOMTimeout) {
  8334. clearTimeout(this.#moveInDOMTimeout);
  8335. this.#moveInDOMTimeout = null;
  8336. }
  8337. this.#stopResizing();
  8338. this.removeEditToolbar();
  8339. if (this.#telemetryTimeouts) {
  8340. for (const timeout of this.#telemetryTimeouts.values()) {
  8341. clearTimeout(timeout);
  8342. }
  8343. this.#telemetryTimeouts = null;
  8344. }
  8345. this.parent = null;
  8346. }
  8347. get isResizable() {
  8348. return false;
  8349. }
  8350. makeResizable() {
  8351. if (this.isResizable) {
  8352. this.#createResizers();
  8353. this.#resizersDiv.classList.remove("hidden");
  8354. bindEvents(this, this.div, ["keydown"]);
  8355. }
  8356. }
  8357. get toolbarPosition() {
  8358. return null;
  8359. }
  8360. keydown(event) {
  8361. if (!this.isResizable || event.target !== this.div || event.key !== "Enter") {
  8362. return;
  8363. }
  8364. this._uiManager.setSelected(this);
  8365. this.#savedDimensions = {
  8366. savedX: this.x,
  8367. savedY: this.y,
  8368. savedWidth: this.width,
  8369. savedHeight: this.height
  8370. };
  8371. const children = this.#resizersDiv.children;
  8372. if (!this.#allResizerDivs) {
  8373. this.#allResizerDivs = Array.from(children);
  8374. const boundResizerKeydown = this.#resizerKeydown.bind(this);
  8375. const boundResizerBlur = this.#resizerBlur.bind(this);
  8376. const signal = this._uiManager._signal;
  8377. for (const div of this.#allResizerDivs) {
  8378. const name = div.getAttribute("data-resizer-name");
  8379. div.setAttribute("role", "spinbutton");
  8380. div.addEventListener("keydown", boundResizerKeydown, {
  8381. signal
  8382. });
  8383. div.addEventListener("blur", boundResizerBlur, {
  8384. signal
  8385. });
  8386. div.addEventListener("focus", this.#resizerFocus.bind(this, name), {
  8387. signal
  8388. });
  8389. div.setAttribute("data-l10n-id", AnnotationEditor._l10nResizer[name]);
  8390. }
  8391. }
  8392. const first = this.#allResizerDivs[0];
  8393. let firstPosition = 0;
  8394. for (const div of children) {
  8395. if (div === first) {
  8396. break;
  8397. }
  8398. firstPosition++;
  8399. }
  8400. const nextFirstPosition = (360 - this.rotation + this.parentRotation) % 360 / 90 * (this.#allResizerDivs.length / 4);
  8401. if (nextFirstPosition !== firstPosition) {
  8402. if (nextFirstPosition < firstPosition) {
  8403. for (let i = 0; i < firstPosition - nextFirstPosition; i++) {
  8404. this.#resizersDiv.append(this.#resizersDiv.firstChild);
  8405. }
  8406. } else if (nextFirstPosition > firstPosition) {
  8407. for (let i = 0; i < nextFirstPosition - firstPosition; i++) {
  8408. this.#resizersDiv.firstChild.before(this.#resizersDiv.lastChild);
  8409. }
  8410. }
  8411. let i = 0;
  8412. for (const child of children) {
  8413. const div = this.#allResizerDivs[i++];
  8414. const name = div.getAttribute("data-resizer-name");
  8415. child.setAttribute("data-l10n-id", AnnotationEditor._l10nResizer[name]);
  8416. }
  8417. }
  8418. this.#setResizerTabIndex(0);
  8419. this.#isResizerEnabledForKeyboard = true;
  8420. this.#resizersDiv.firstChild.focus({
  8421. focusVisible: true
  8422. });
  8423. event.preventDefault();
  8424. event.stopImmediatePropagation();
  8425. }
  8426. #resizerKeydown(event) {
  8427. AnnotationEditor._resizerKeyboardManager.exec(this, event);
  8428. }
  8429. #resizerBlur(event) {
  8430. if (this.#isResizerEnabledForKeyboard && event.relatedTarget?.parentNode !== this.#resizersDiv) {
  8431. this.#stopResizing();
  8432. }
  8433. }
  8434. #resizerFocus(name) {
  8435. this.#focusedResizerName = this.#isResizerEnabledForKeyboard ? name : "";
  8436. }
  8437. #setResizerTabIndex(value) {
  8438. if (!this.#allResizerDivs) {
  8439. return;
  8440. }
  8441. for (const div of this.#allResizerDivs) {
  8442. div.tabIndex = value;
  8443. }
  8444. }
  8445. _resizeWithKeyboard(x, y) {
  8446. if (!this.#isResizerEnabledForKeyboard) {
  8447. return;
  8448. }
  8449. this.#resizerPointermove(this.#focusedResizerName, {
  8450. movementX: x,
  8451. movementY: y
  8452. });
  8453. }
  8454. #stopResizing() {
  8455. this.#isResizerEnabledForKeyboard = false;
  8456. this.#setResizerTabIndex(-1);
  8457. if (this.#savedDimensions) {
  8458. const {
  8459. savedX,
  8460. savedY,
  8461. savedWidth,
  8462. savedHeight
  8463. } = this.#savedDimensions;
  8464. this.#addResizeToUndoStack(savedX, savedY, savedWidth, savedHeight);
  8465. this.#savedDimensions = null;
  8466. }
  8467. }
  8468. _stopResizingWithKeyboard() {
  8469. this.#stopResizing();
  8470. this.div.focus();
  8471. }
  8472. select() {
  8473. this.makeResizable();
  8474. this.div?.classList.add("selectedEditor");
  8475. if (!this._editToolbar) {
  8476. this.addEditToolbar().then(() => {
  8477. if (this.div?.classList.contains("selectedEditor")) {
  8478. this._editToolbar?.show();
  8479. }
  8480. });
  8481. return;
  8482. }
  8483. this._editToolbar?.show();
  8484. this.#altText?.toggleAltTextBadge(false);
  8485. }
  8486. unselect() {
  8487. this.#resizersDiv?.classList.add("hidden");
  8488. this.div?.classList.remove("selectedEditor");
  8489. if (this.div?.contains(document.activeElement)) {
  8490. this._uiManager.currentLayer.div.focus({
  8491. preventScroll: true
  8492. });
  8493. }
  8494. this._editToolbar?.hide();
  8495. this.#altText?.toggleAltTextBadge(true);
  8496. }
  8497. updateParams(type, value) {}
  8498. disableEditing() {}
  8499. enableEditing() {}
  8500. enterInEditMode() {}
  8501. getImageForAltText() {
  8502. return null;
  8503. }
  8504. get contentDiv() {
  8505. return this.div;
  8506. }
  8507. get isEditing() {
  8508. return this.#isEditing;
  8509. }
  8510. set isEditing(value) {
  8511. this.#isEditing = value;
  8512. if (!this.parent) {
  8513. return;
  8514. }
  8515. if (value) {
  8516. this.parent.setSelected(this);
  8517. this.parent.setActiveEditor(this);
  8518. } else {
  8519. this.parent.setActiveEditor(null);
  8520. }
  8521. }
  8522. setAspectRatio(width, height) {
  8523. this.#keepAspectRatio = true;
  8524. const aspectRatio = width / height;
  8525. const {
  8526. style
  8527. } = this.div;
  8528. style.aspectRatio = aspectRatio;
  8529. style.height = "auto";
  8530. }
  8531. static get MIN_SIZE() {
  8532. return 16;
  8533. }
  8534. static canCreateNewEmptyEditor() {
  8535. return true;
  8536. }
  8537. get telemetryInitialData() {
  8538. return {
  8539. action: "added"
  8540. };
  8541. }
  8542. get telemetryFinalData() {
  8543. return null;
  8544. }
  8545. _reportTelemetry(data, mustWait = false) {
  8546. if (mustWait) {
  8547. this.#telemetryTimeouts ||= new Map();
  8548. const {
  8549. action
  8550. } = data;
  8551. let timeout = this.#telemetryTimeouts.get(action);
  8552. if (timeout) {
  8553. clearTimeout(timeout);
  8554. }
  8555. timeout = setTimeout(() => {
  8556. this._reportTelemetry(data);
  8557. this.#telemetryTimeouts.delete(action);
  8558. if (this.#telemetryTimeouts.size === 0) {
  8559. this.#telemetryTimeouts = null;
  8560. }
  8561. }, AnnotationEditor._telemetryTimeout);
  8562. this.#telemetryTimeouts.set(action, timeout);
  8563. return;
  8564. }
  8565. data.type ||= this.editorType;
  8566. this._uiManager._eventBus.dispatch("reporttelemetry", {
  8567. source: this,
  8568. details: {
  8569. type: "editing",
  8570. data
  8571. }
  8572. });
  8573. }
  8574. show(visible = this._isVisible) {
  8575. this.div.classList.toggle("hidden", !visible);
  8576. this._isVisible = visible;
  8577. }
  8578. enable() {
  8579. if (this.div) {
  8580. this.div.tabIndex = 0;
  8581. }
  8582. this.#disabled = false;
  8583. }
  8584. disable() {
  8585. if (this.div) {
  8586. this.div.tabIndex = -1;
  8587. }
  8588. this.#disabled = true;
  8589. }
  8590. renderAnnotationElement(annotation) {
  8591. let content = annotation.container.querySelector(".annotationContent");
  8592. if (!content) {
  8593. content = document.createElement("div");
  8594. content.classList.add("annotationContent", this.editorType);
  8595. annotation.container.prepend(content);
  8596. } else if (content.nodeName === "CANVAS") {
  8597. const canvas = content;
  8598. content = document.createElement("div");
  8599. content.classList.add("annotationContent", this.editorType);
  8600. canvas.before(content);
  8601. }
  8602. return content;
  8603. }
  8604. resetAnnotationElement(annotation) {
  8605. const {
  8606. firstChild
  8607. } = annotation.container;
  8608. if (firstChild?.nodeName === "DIV" && firstChild.classList.contains("annotationContent")) {
  8609. firstChild.remove();
  8610. }
  8611. }
  8612. }
  8613. class FakeEditor extends AnnotationEditor {
  8614. constructor(params) {
  8615. super(params);
  8616. this.annotationElementId = params.annotationElementId;
  8617. this.deleted = true;
  8618. }
  8619. serialize() {
  8620. return this.serializeDeleted();
  8621. }
  8622. }
  8623. ;// ./src/shared/murmurhash3.js
  8624. const SEED = 0xc3d2e1f0;
  8625. const MASK_HIGH = 0xffff0000;
  8626. const MASK_LOW = 0xffff;
  8627. class MurmurHash3_64 {
  8628. constructor(seed) {
  8629. this.h1 = seed ? seed & 0xffffffff : SEED;
  8630. this.h2 = seed ? seed & 0xffffffff : SEED;
  8631. }
  8632. update(input) {
  8633. let data, length;
  8634. if (typeof input === "string") {
  8635. data = new Uint8Array(input.length * 2);
  8636. length = 0;
  8637. for (let i = 0, ii = input.length; i < ii; i++) {
  8638. const code = input.charCodeAt(i);
  8639. if (code <= 0xff) {
  8640. data[length++] = code;
  8641. } else {
  8642. data[length++] = code >>> 8;
  8643. data[length++] = code & 0xff;
  8644. }
  8645. }
  8646. } else if (ArrayBuffer.isView(input)) {
  8647. data = input.slice();
  8648. length = data.byteLength;
  8649. } else {
  8650. throw new Error("Invalid data format, must be a string or TypedArray.");
  8651. }
  8652. const blockCounts = length >> 2;
  8653. const tailLength = length - blockCounts * 4;
  8654. const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);
  8655. let k1 = 0,
  8656. k2 = 0;
  8657. let h1 = this.h1,
  8658. h2 = this.h2;
  8659. const C1 = 0xcc9e2d51,
  8660. C2 = 0x1b873593;
  8661. const C1_LOW = C1 & MASK_LOW,
  8662. C2_LOW = C2 & MASK_LOW;
  8663. for (let i = 0; i < blockCounts; i++) {
  8664. if (i & 1) {
  8665. k1 = dataUint32[i];
  8666. k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
  8667. k1 = k1 << 15 | k1 >>> 17;
  8668. k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
  8669. h1 ^= k1;
  8670. h1 = h1 << 13 | h1 >>> 19;
  8671. h1 = h1 * 5 + 0xe6546b64;
  8672. } else {
  8673. k2 = dataUint32[i];
  8674. k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW;
  8675. k2 = k2 << 15 | k2 >>> 17;
  8676. k2 = k2 * C2 & MASK_HIGH | k2 * C2_LOW & MASK_LOW;
  8677. h2 ^= k2;
  8678. h2 = h2 << 13 | h2 >>> 19;
  8679. h2 = h2 * 5 + 0xe6546b64;
  8680. }
  8681. }
  8682. k1 = 0;
  8683. switch (tailLength) {
  8684. case 3:
  8685. k1 ^= data[blockCounts * 4 + 2] << 16;
  8686. case 2:
  8687. k1 ^= data[blockCounts * 4 + 1] << 8;
  8688. case 1:
  8689. k1 ^= data[blockCounts * 4];
  8690. k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
  8691. k1 = k1 << 15 | k1 >>> 17;
  8692. k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
  8693. if (blockCounts & 1) {
  8694. h1 ^= k1;
  8695. } else {
  8696. h2 ^= k1;
  8697. }
  8698. }
  8699. this.h1 = h1;
  8700. this.h2 = h2;
  8701. }
  8702. hexdigest() {
  8703. let h1 = this.h1,
  8704. h2 = this.h2;
  8705. h1 ^= h2 >>> 1;
  8706. h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW;
  8707. h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16;
  8708. h1 ^= h2 >>> 1;
  8709. h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW;
  8710. h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16;
  8711. h1 ^= h2 >>> 1;
  8712. return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0");
  8713. }
  8714. }
  8715. ;// ./src/display/annotation_storage.js
  8716. const SerializableEmpty = Object.freeze({
  8717. map: null,
  8718. hash: "",
  8719. transfer: undefined
  8720. });
  8721. class AnnotationStorage {
  8722. #modified = false;
  8723. #modifiedIds = null;
  8724. #storage = new Map();
  8725. constructor() {
  8726. this.onSetModified = null;
  8727. this.onResetModified = null;
  8728. this.onAnnotationEditor = null;
  8729. }
  8730. getValue(key, defaultValue) {
  8731. const value = this.#storage.get(key);
  8732. if (value === undefined) {
  8733. return defaultValue;
  8734. }
  8735. return Object.assign(defaultValue, value);
  8736. }
  8737. getRawValue(key) {
  8738. return this.#storage.get(key);
  8739. }
  8740. remove(key) {
  8741. this.#storage.delete(key);
  8742. if (this.#storage.size === 0) {
  8743. this.resetModified();
  8744. }
  8745. if (typeof this.onAnnotationEditor === "function") {
  8746. for (const value of this.#storage.values()) {
  8747. if (value instanceof AnnotationEditor) {
  8748. return;
  8749. }
  8750. }
  8751. this.onAnnotationEditor(null);
  8752. }
  8753. }
  8754. setValue(key, value) {
  8755. const obj = this.#storage.get(key);
  8756. let modified = false;
  8757. if (obj !== undefined) {
  8758. for (const [entry, val] of Object.entries(value)) {
  8759. if (obj[entry] !== val) {
  8760. modified = true;
  8761. obj[entry] = val;
  8762. }
  8763. }
  8764. } else {
  8765. modified = true;
  8766. this.#storage.set(key, value);
  8767. }
  8768. if (modified) {
  8769. this.#setModified();
  8770. }
  8771. if (value instanceof AnnotationEditor && typeof this.onAnnotationEditor === "function") {
  8772. this.onAnnotationEditor(value.constructor._type);
  8773. }
  8774. }
  8775. has(key) {
  8776. return this.#storage.has(key);
  8777. }
  8778. getAll() {
  8779. return this.#storage.size > 0 ? objectFromMap(this.#storage) : null;
  8780. }
  8781. setAll(obj) {
  8782. for (const [key, val] of Object.entries(obj)) {
  8783. this.setValue(key, val);
  8784. }
  8785. }
  8786. get size() {
  8787. return this.#storage.size;
  8788. }
  8789. #setModified() {
  8790. if (!this.#modified) {
  8791. this.#modified = true;
  8792. if (typeof this.onSetModified === "function") {
  8793. this.onSetModified();
  8794. }
  8795. }
  8796. }
  8797. resetModified() {
  8798. if (this.#modified) {
  8799. this.#modified = false;
  8800. if (typeof this.onResetModified === "function") {
  8801. this.onResetModified();
  8802. }
  8803. }
  8804. }
  8805. get print() {
  8806. return new PrintAnnotationStorage(this);
  8807. }
  8808. get serializable() {
  8809. if (this.#storage.size === 0) {
  8810. return SerializableEmpty;
  8811. }
  8812. const map = new Map(),
  8813. hash = new MurmurHash3_64(),
  8814. transfer = [];
  8815. const context = Object.create(null);
  8816. let hasBitmap = false;
  8817. for (const [key, val] of this.#storage) {
  8818. const serialized = val instanceof AnnotationEditor ? val.serialize(false, context) : val;
  8819. if (serialized) {
  8820. map.set(key, serialized);
  8821. hash.update(`${key}:${JSON.stringify(serialized)}`);
  8822. hasBitmap ||= !!serialized.bitmap;
  8823. }
  8824. }
  8825. if (hasBitmap) {
  8826. for (const value of map.values()) {
  8827. if (value.bitmap) {
  8828. transfer.push(value.bitmap);
  8829. }
  8830. }
  8831. }
  8832. return map.size > 0 ? {
  8833. map,
  8834. hash: hash.hexdigest(),
  8835. transfer
  8836. } : SerializableEmpty;
  8837. }
  8838. get editorStats() {
  8839. let stats = null;
  8840. const typeToEditor = new Map();
  8841. for (const value of this.#storage.values()) {
  8842. if (!(value instanceof AnnotationEditor)) {
  8843. continue;
  8844. }
  8845. const editorStats = value.telemetryFinalData;
  8846. if (!editorStats) {
  8847. continue;
  8848. }
  8849. const {
  8850. type
  8851. } = editorStats;
  8852. if (!typeToEditor.has(type)) {
  8853. typeToEditor.set(type, Object.getPrototypeOf(value).constructor);
  8854. }
  8855. stats ||= Object.create(null);
  8856. const map = stats[type] ||= new Map();
  8857. for (const [key, val] of Object.entries(editorStats)) {
  8858. if (key === "type") {
  8859. continue;
  8860. }
  8861. let counters = map.get(key);
  8862. if (!counters) {
  8863. counters = new Map();
  8864. map.set(key, counters);
  8865. }
  8866. const count = counters.get(val) ?? 0;
  8867. counters.set(val, count + 1);
  8868. }
  8869. }
  8870. for (const [type, editor] of typeToEditor) {
  8871. stats[type] = editor.computeTelemetryFinalData(stats[type]);
  8872. }
  8873. return stats;
  8874. }
  8875. resetModifiedIds() {
  8876. this.#modifiedIds = null;
  8877. }
  8878. get modifiedIds() {
  8879. if (this.#modifiedIds) {
  8880. return this.#modifiedIds;
  8881. }
  8882. const ids = [];
  8883. for (const value of this.#storage.values()) {
  8884. if (!(value instanceof AnnotationEditor) || !value.annotationElementId || !value.serialize()) {
  8885. continue;
  8886. }
  8887. ids.push(value.annotationElementId);
  8888. }
  8889. return this.#modifiedIds = {
  8890. ids: new Set(ids),
  8891. hash: ids.join(",")
  8892. };
  8893. }
  8894. }
  8895. class PrintAnnotationStorage extends AnnotationStorage {
  8896. #serializable;
  8897. constructor(parent) {
  8898. super();
  8899. const {
  8900. map,
  8901. hash,
  8902. transfer
  8903. } = parent.serializable;
  8904. const clone = structuredClone(map, transfer ? {
  8905. transfer
  8906. } : null);
  8907. this.#serializable = {
  8908. map: clone,
  8909. hash,
  8910. transfer
  8911. };
  8912. }
  8913. get print() {
  8914. unreachable("Should not call PrintAnnotationStorage.print");
  8915. }
  8916. get serializable() {
  8917. return this.#serializable;
  8918. }
  8919. get modifiedIds() {
  8920. return shadow(this, "modifiedIds", {
  8921. ids: new Set(),
  8922. hash: ""
  8923. });
  8924. }
  8925. }
  8926. ;// ./src/display/font_loader.js
  8927. class FontLoader {
  8928. #systemFonts = new Set();
  8929. constructor({
  8930. ownerDocument = globalThis.document,
  8931. styleElement = null
  8932. }) {
  8933. this._document = ownerDocument;
  8934. this.nativeFontFaces = new Set();
  8935. this.styleElement = null;
  8936. this.loadingRequests = [];
  8937. this.loadTestFontId = 0;
  8938. }
  8939. addNativeFontFace(nativeFontFace) {
  8940. this.nativeFontFaces.add(nativeFontFace);
  8941. this._document.fonts.add(nativeFontFace);
  8942. }
  8943. removeNativeFontFace(nativeFontFace) {
  8944. this.nativeFontFaces.delete(nativeFontFace);
  8945. this._document.fonts.delete(nativeFontFace);
  8946. }
  8947. insertRule(rule) {
  8948. if (!this.styleElement) {
  8949. this.styleElement = this._document.createElement("style");
  8950. this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement);
  8951. }
  8952. const styleSheet = this.styleElement.sheet;
  8953. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  8954. }
  8955. clear() {
  8956. for (const nativeFontFace of this.nativeFontFaces) {
  8957. this._document.fonts.delete(nativeFontFace);
  8958. }
  8959. this.nativeFontFaces.clear();
  8960. this.#systemFonts.clear();
  8961. if (this.styleElement) {
  8962. this.styleElement.remove();
  8963. this.styleElement = null;
  8964. }
  8965. }
  8966. async loadSystemFont({
  8967. systemFontInfo: info,
  8968. _inspectFont
  8969. }) {
  8970. if (!info || this.#systemFonts.has(info.loadedName)) {
  8971. return;
  8972. }
  8973. assert(!this.disableFontFace, "loadSystemFont shouldn't be called when `disableFontFace` is set.");
  8974. if (this.isFontLoadingAPISupported) {
  8975. const {
  8976. loadedName,
  8977. src,
  8978. style
  8979. } = info;
  8980. const fontFace = new FontFace(loadedName, src, style);
  8981. this.addNativeFontFace(fontFace);
  8982. try {
  8983. await fontFace.load();
  8984. this.#systemFonts.add(loadedName);
  8985. _inspectFont?.(info);
  8986. } catch {
  8987. warn(`Cannot load system font: ${info.baseFontName}, installing it could help to improve PDF rendering.`);
  8988. this.removeNativeFontFace(fontFace);
  8989. }
  8990. return;
  8991. }
  8992. unreachable("Not implemented: loadSystemFont without the Font Loading API.");
  8993. }
  8994. async bind(font) {
  8995. if (font.attached || font.missingFile && !font.systemFontInfo) {
  8996. return;
  8997. }
  8998. font.attached = true;
  8999. if (font.systemFontInfo) {
  9000. await this.loadSystemFont(font);
  9001. return;
  9002. }
  9003. if (this.isFontLoadingAPISupported) {
  9004. const nativeFontFace = font.createNativeFontFace();
  9005. if (nativeFontFace) {
  9006. this.addNativeFontFace(nativeFontFace);
  9007. try {
  9008. await nativeFontFace.loaded;
  9009. } catch (ex) {
  9010. warn(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
  9011. font.disableFontFace = true;
  9012. throw ex;
  9013. }
  9014. }
  9015. return;
  9016. }
  9017. const rule = font.createFontFaceRule();
  9018. if (rule) {
  9019. this.insertRule(rule);
  9020. if (this.isSyncFontLoadingSupported) {
  9021. return;
  9022. }
  9023. await new Promise(resolve => {
  9024. const request = this._queueLoadingCallback(resolve);
  9025. this._prepareFontLoadEvent(font, request);
  9026. });
  9027. }
  9028. }
  9029. get isFontLoadingAPISupported() {
  9030. const hasFonts = !!this._document?.fonts;
  9031. return shadow(this, "isFontLoadingAPISupported", hasFonts);
  9032. }
  9033. get isSyncFontLoadingSupported() {
  9034. let supported = false;
  9035. if (isNodeJS) {
  9036. supported = true;
  9037. } else if (typeof navigator !== "undefined" && typeof navigator?.userAgent === "string" && /Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent)) {
  9038. supported = true;
  9039. }
  9040. return shadow(this, "isSyncFontLoadingSupported", supported);
  9041. }
  9042. _queueLoadingCallback(callback) {
  9043. function completeRequest() {
  9044. assert(!request.done, "completeRequest() cannot be called twice.");
  9045. request.done = true;
  9046. while (loadingRequests.length > 0 && loadingRequests[0].done) {
  9047. const otherRequest = loadingRequests.shift();
  9048. setTimeout(otherRequest.callback, 0);
  9049. }
  9050. }
  9051. const {
  9052. loadingRequests
  9053. } = this;
  9054. const request = {
  9055. done: false,
  9056. complete: completeRequest,
  9057. callback
  9058. };
  9059. loadingRequests.push(request);
  9060. return request;
  9061. }
  9062. get _loadTestFont() {
  9063. const testFont = atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQA" + "FQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAA" + "ALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgA" + "AAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1" + "AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD" + "6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACM" + "AooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4D" + "IP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAA" + "AAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUA" + "AQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgAB" + "AAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABY" + "AAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAA" + "AC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAA" + "AAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQAC" + "AQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3" + "Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTj" + "FQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");
  9064. return shadow(this, "_loadTestFont", testFont);
  9065. }
  9066. _prepareFontLoadEvent(font, request) {
  9067. function int32(data, offset) {
  9068. return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
  9069. }
  9070. function spliceString(s, offset, remove, insert) {
  9071. const chunk1 = s.substring(0, offset);
  9072. const chunk2 = s.substring(offset + remove);
  9073. return chunk1 + insert + chunk2;
  9074. }
  9075. let i, ii;
  9076. const canvas = this._document.createElement("canvas");
  9077. canvas.width = 1;
  9078. canvas.height = 1;
  9079. const ctx = canvas.getContext("2d");
  9080. let called = 0;
  9081. function isFontReady(name, callback) {
  9082. if (++called > 30) {
  9083. warn("Load test font never loaded.");
  9084. callback();
  9085. return;
  9086. }
  9087. ctx.font = "30px " + name;
  9088. ctx.fillText(".", 0, 20);
  9089. const imageData = ctx.getImageData(0, 0, 1, 1);
  9090. if (imageData.data[3] > 0) {
  9091. callback();
  9092. return;
  9093. }
  9094. setTimeout(isFontReady.bind(null, name, callback));
  9095. }
  9096. const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
  9097. let data = this._loadTestFont;
  9098. const COMMENT_OFFSET = 976;
  9099. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
  9100. const CFF_CHECKSUM_OFFSET = 16;
  9101. const XXXX_VALUE = 0x58585858;
  9102. let checksum = int32(data, CFF_CHECKSUM_OFFSET);
  9103. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  9104. checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
  9105. }
  9106. if (i < loadTestFontId.length) {
  9107. checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
  9108. }
  9109. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  9110. const url = `url(data:font/opentype;base64,${btoa(data)});`;
  9111. const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
  9112. this.insertRule(rule);
  9113. const div = this._document.createElement("div");
  9114. div.style.visibility = "hidden";
  9115. div.style.width = div.style.height = "10px";
  9116. div.style.position = "absolute";
  9117. div.style.top = div.style.left = "0px";
  9118. for (const name of [font.loadedName, loadTestFontId]) {
  9119. const span = this._document.createElement("span");
  9120. span.textContent = "Hi";
  9121. span.style.fontFamily = name;
  9122. div.append(span);
  9123. }
  9124. this._document.body.append(div);
  9125. isFontReady(loadTestFontId, () => {
  9126. div.remove();
  9127. request.complete();
  9128. });
  9129. }
  9130. }
  9131. class FontFaceObject {
  9132. constructor(translatedData, {
  9133. disableFontFace = false,
  9134. inspectFont = null
  9135. }) {
  9136. this.compiledGlyphs = Object.create(null);
  9137. for (const i in translatedData) {
  9138. this[i] = translatedData[i];
  9139. }
  9140. this.disableFontFace = disableFontFace === true;
  9141. this._inspectFont = inspectFont;
  9142. }
  9143. createNativeFontFace() {
  9144. if (!this.data || this.disableFontFace) {
  9145. return null;
  9146. }
  9147. let nativeFontFace;
  9148. if (!this.cssFontInfo) {
  9149. nativeFontFace = new FontFace(this.loadedName, this.data, {});
  9150. } else {
  9151. const css = {
  9152. weight: this.cssFontInfo.fontWeight
  9153. };
  9154. if (this.cssFontInfo.italicAngle) {
  9155. css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
  9156. }
  9157. nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);
  9158. }
  9159. this._inspectFont?.(this);
  9160. return nativeFontFace;
  9161. }
  9162. createFontFaceRule() {
  9163. if (!this.data || this.disableFontFace) {
  9164. return null;
  9165. }
  9166. const data = bytesToString(this.data);
  9167. const url = `url(data:${this.mimetype};base64,${btoa(data)});`;
  9168. let rule;
  9169. if (!this.cssFontInfo) {
  9170. rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
  9171. } else {
  9172. let css = `font-weight: ${this.cssFontInfo.fontWeight};`;
  9173. if (this.cssFontInfo.italicAngle) {
  9174. css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
  9175. }
  9176. rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;
  9177. }
  9178. this._inspectFont?.(this, url);
  9179. return rule;
  9180. }
  9181. getPathGenerator(objs, character) {
  9182. if (this.compiledGlyphs[character] !== undefined) {
  9183. return this.compiledGlyphs[character];
  9184. }
  9185. let cmds;
  9186. try {
  9187. cmds = objs.get(this.loadedName + "_path_" + character);
  9188. } catch (ex) {
  9189. warn(`getPathGenerator - ignoring character: "${ex}".`);
  9190. }
  9191. if (!Array.isArray(cmds) || cmds.length === 0) {
  9192. return this.compiledGlyphs[character] = function (c, size) {};
  9193. }
  9194. const commands = [];
  9195. for (let i = 0, ii = cmds.length; i < ii;) {
  9196. switch (cmds[i++]) {
  9197. case FontRenderOps.BEZIER_CURVE_TO:
  9198. {
  9199. const [a, b, c, d, e, f] = cmds.slice(i, i + 6);
  9200. commands.push(ctx => ctx.bezierCurveTo(a, b, c, d, e, f));
  9201. i += 6;
  9202. }
  9203. break;
  9204. case FontRenderOps.MOVE_TO:
  9205. {
  9206. const [a, b] = cmds.slice(i, i + 2);
  9207. commands.push(ctx => ctx.moveTo(a, b));
  9208. i += 2;
  9209. }
  9210. break;
  9211. case FontRenderOps.LINE_TO:
  9212. {
  9213. const [a, b] = cmds.slice(i, i + 2);
  9214. commands.push(ctx => ctx.lineTo(a, b));
  9215. i += 2;
  9216. }
  9217. break;
  9218. case FontRenderOps.QUADRATIC_CURVE_TO:
  9219. {
  9220. const [a, b, c, d] = cmds.slice(i, i + 4);
  9221. commands.push(ctx => ctx.quadraticCurveTo(a, b, c, d));
  9222. i += 4;
  9223. }
  9224. break;
  9225. case FontRenderOps.RESTORE:
  9226. commands.push(ctx => ctx.restore());
  9227. break;
  9228. case FontRenderOps.SAVE:
  9229. commands.push(ctx => ctx.save());
  9230. break;
  9231. case FontRenderOps.SCALE:
  9232. assert(commands.length === 2, "Scale command is only valid at the third position.");
  9233. break;
  9234. case FontRenderOps.TRANSFORM:
  9235. {
  9236. const [a, b, c, d, e, f] = cmds.slice(i, i + 6);
  9237. commands.push(ctx => ctx.transform(a, b, c, d, e, f));
  9238. i += 6;
  9239. }
  9240. break;
  9241. case FontRenderOps.TRANSLATE:
  9242. {
  9243. const [a, b] = cmds.slice(i, i + 2);
  9244. commands.push(ctx => ctx.translate(a, b));
  9245. i += 2;
  9246. }
  9247. break;
  9248. }
  9249. }
  9250. return this.compiledGlyphs[character] = function glyphDrawer(ctx, size) {
  9251. commands[0](ctx);
  9252. commands[1](ctx);
  9253. ctx.scale(size, -size);
  9254. for (let i = 2, ii = commands.length; i < ii; i++) {
  9255. commands[i](ctx);
  9256. }
  9257. };
  9258. }
  9259. }
  9260. ;// ./src/display/node_utils.js
  9261. if (isNodeJS) {
  9262. var packageCapability = Promise.withResolvers();
  9263. var packageMap = null;
  9264. const loadPackages = async () => {
  9265. const fs = await import(/*webpackIgnore: true*/"fs"),
  9266. http = await import(/*webpackIgnore: true*/"http"),
  9267. https = await import(/*webpackIgnore: true*/"https"),
  9268. url = await import(/*webpackIgnore: true*/"url");
  9269. let canvas, path2d;
  9270. try {
  9271. canvas = await import(/*webpackIgnore: true*/"canvas");
  9272. } catch {}
  9273. try {
  9274. path2d = await import(/*webpackIgnore: true*/"path2d");
  9275. } catch {}
  9276. return new Map(Object.entries({
  9277. fs,
  9278. http,
  9279. https,
  9280. url,
  9281. canvas,
  9282. path2d
  9283. }));
  9284. };
  9285. loadPackages().then(map => {
  9286. packageMap = map;
  9287. packageCapability.resolve();
  9288. if (!globalThis.DOMMatrix) {
  9289. const DOMMatrix = map.get("canvas")?.DOMMatrix;
  9290. if (DOMMatrix) {
  9291. globalThis.DOMMatrix = DOMMatrix;
  9292. } else {
  9293. warn("Cannot polyfill `DOMMatrix`, rendering may be broken.");
  9294. }
  9295. }
  9296. if (!globalThis.Path2D) {
  9297. const CanvasRenderingContext2D = map.get("canvas")?.CanvasRenderingContext2D;
  9298. const applyPath2DToCanvasRenderingContext = map.get("path2d")?.applyPath2DToCanvasRenderingContext;
  9299. const Path2D = map.get("path2d")?.Path2D;
  9300. if (CanvasRenderingContext2D && applyPath2DToCanvasRenderingContext && Path2D) {
  9301. applyPath2DToCanvasRenderingContext(CanvasRenderingContext2D);
  9302. globalThis.Path2D = Path2D;
  9303. } else {
  9304. warn("Cannot polyfill `Path2D`, rendering may be broken.");
  9305. }
  9306. }
  9307. }, reason => {
  9308. warn(`loadPackages: ${reason}`);
  9309. packageMap = new Map();
  9310. packageCapability.resolve();
  9311. });
  9312. }
  9313. class NodePackages {
  9314. static get promise() {
  9315. return packageCapability.promise;
  9316. }
  9317. static get(name) {
  9318. return packageMap?.get(name);
  9319. }
  9320. }
  9321. const node_utils_fetchData = function (url) {
  9322. const fs = NodePackages.get("fs");
  9323. return fs.promises.readFile(url).then(data => new Uint8Array(data));
  9324. };
  9325. class NodeFilterFactory extends BaseFilterFactory {}
  9326. class NodeCanvasFactory extends BaseCanvasFactory {
  9327. _createCanvas(width, height) {
  9328. const canvas = NodePackages.get("canvas");
  9329. return canvas.createCanvas(width, height);
  9330. }
  9331. }
  9332. class NodeCMapReaderFactory extends BaseCMapReaderFactory {
  9333. _fetchData(url, compressionType) {
  9334. return node_utils_fetchData(url).then(data => ({
  9335. cMapData: data,
  9336. compressionType
  9337. }));
  9338. }
  9339. }
  9340. class NodeStandardFontDataFactory extends BaseStandardFontDataFactory {
  9341. _fetchData(url) {
  9342. return node_utils_fetchData(url);
  9343. }
  9344. }
  9345. ;// ./src/display/pattern_helper.js
  9346. const PathType = {
  9347. FILL: "Fill",
  9348. STROKE: "Stroke",
  9349. SHADING: "Shading"
  9350. };
  9351. function applyBoundingBox(ctx, bbox) {
  9352. if (!bbox) {
  9353. return;
  9354. }
  9355. const width = bbox[2] - bbox[0];
  9356. const height = bbox[3] - bbox[1];
  9357. const region = new Path2D();
  9358. region.rect(bbox[0], bbox[1], width, height);
  9359. ctx.clip(region);
  9360. }
  9361. class BaseShadingPattern {
  9362. getPattern() {
  9363. unreachable("Abstract method `getPattern` called.");
  9364. }
  9365. }
  9366. class RadialAxialShadingPattern extends BaseShadingPattern {
  9367. constructor(IR) {
  9368. super();
  9369. this._type = IR[1];
  9370. this._bbox = IR[2];
  9371. this._colorStops = IR[3];
  9372. this._p0 = IR[4];
  9373. this._p1 = IR[5];
  9374. this._r0 = IR[6];
  9375. this._r1 = IR[7];
  9376. this.matrix = null;
  9377. }
  9378. _createGradient(ctx) {
  9379. let grad;
  9380. if (this._type === "axial") {
  9381. grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
  9382. } else if (this._type === "radial") {
  9383. grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
  9384. }
  9385. for (const colorStop of this._colorStops) {
  9386. grad.addColorStop(colorStop[0], colorStop[1]);
  9387. }
  9388. return grad;
  9389. }
  9390. getPattern(ctx, owner, inverse, pathType) {
  9391. let pattern;
  9392. if (pathType === PathType.STROKE || pathType === PathType.FILL) {
  9393. const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, getCurrentTransform(ctx)) || [0, 0, 0, 0];
  9394. const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;
  9395. const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;
  9396. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height);
  9397. const tmpCtx = tmpCanvas.context;
  9398. tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  9399. tmpCtx.beginPath();
  9400. tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  9401. tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);
  9402. inverse = Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]);
  9403. tmpCtx.transform(...owner.baseTransform);
  9404. if (this.matrix) {
  9405. tmpCtx.transform(...this.matrix);
  9406. }
  9407. applyBoundingBox(tmpCtx, this._bbox);
  9408. tmpCtx.fillStyle = this._createGradient(tmpCtx);
  9409. tmpCtx.fill();
  9410. pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat");
  9411. const domMatrix = new DOMMatrix(inverse);
  9412. pattern.setTransform(domMatrix);
  9413. } else {
  9414. applyBoundingBox(ctx, this._bbox);
  9415. pattern = this._createGradient(ctx);
  9416. }
  9417. return pattern;
  9418. }
  9419. }
  9420. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  9421. const coords = context.coords,
  9422. colors = context.colors;
  9423. const bytes = data.data,
  9424. rowSize = data.width * 4;
  9425. let tmp;
  9426. if (coords[p1 + 1] > coords[p2 + 1]) {
  9427. tmp = p1;
  9428. p1 = p2;
  9429. p2 = tmp;
  9430. tmp = c1;
  9431. c1 = c2;
  9432. c2 = tmp;
  9433. }
  9434. if (coords[p2 + 1] > coords[p3 + 1]) {
  9435. tmp = p2;
  9436. p2 = p3;
  9437. p3 = tmp;
  9438. tmp = c2;
  9439. c2 = c3;
  9440. c3 = tmp;
  9441. }
  9442. if (coords[p1 + 1] > coords[p2 + 1]) {
  9443. tmp = p1;
  9444. p1 = p2;
  9445. p2 = tmp;
  9446. tmp = c1;
  9447. c1 = c2;
  9448. c2 = tmp;
  9449. }
  9450. const x1 = (coords[p1] + context.offsetX) * context.scaleX;
  9451. const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  9452. const x2 = (coords[p2] + context.offsetX) * context.scaleX;
  9453. const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  9454. const x3 = (coords[p3] + context.offsetX) * context.scaleX;
  9455. const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  9456. if (y1 >= y3) {
  9457. return;
  9458. }
  9459. const c1r = colors[c1],
  9460. c1g = colors[c1 + 1],
  9461. c1b = colors[c1 + 2];
  9462. const c2r = colors[c2],
  9463. c2g = colors[c2 + 1],
  9464. c2b = colors[c2 + 2];
  9465. const c3r = colors[c3],
  9466. c3g = colors[c3 + 1],
  9467. c3b = colors[c3 + 2];
  9468. const minY = Math.round(y1),
  9469. maxY = Math.round(y3);
  9470. let xa, car, cag, cab;
  9471. let xb, cbr, cbg, cbb;
  9472. for (let y = minY; y <= maxY; y++) {
  9473. if (y < y2) {
  9474. const k = y < y1 ? 0 : (y1 - y) / (y1 - y2);
  9475. xa = x1 - (x1 - x2) * k;
  9476. car = c1r - (c1r - c2r) * k;
  9477. cag = c1g - (c1g - c2g) * k;
  9478. cab = c1b - (c1b - c2b) * k;
  9479. } else {
  9480. let k;
  9481. if (y > y3) {
  9482. k = 1;
  9483. } else if (y2 === y3) {
  9484. k = 0;
  9485. } else {
  9486. k = (y2 - y) / (y2 - y3);
  9487. }
  9488. xa = x2 - (x2 - x3) * k;
  9489. car = c2r - (c2r - c3r) * k;
  9490. cag = c2g - (c2g - c3g) * k;
  9491. cab = c2b - (c2b - c3b) * k;
  9492. }
  9493. let k;
  9494. if (y < y1) {
  9495. k = 0;
  9496. } else if (y > y3) {
  9497. k = 1;
  9498. } else {
  9499. k = (y1 - y) / (y1 - y3);
  9500. }
  9501. xb = x1 - (x1 - x3) * k;
  9502. cbr = c1r - (c1r - c3r) * k;
  9503. cbg = c1g - (c1g - c3g) * k;
  9504. cbb = c1b - (c1b - c3b) * k;
  9505. const x1_ = Math.round(Math.min(xa, xb));
  9506. const x2_ = Math.round(Math.max(xa, xb));
  9507. let j = rowSize * y + x1_ * 4;
  9508. for (let x = x1_; x <= x2_; x++) {
  9509. k = (xa - x) / (xa - xb);
  9510. if (k < 0) {
  9511. k = 0;
  9512. } else if (k > 1) {
  9513. k = 1;
  9514. }
  9515. bytes[j++] = car - (car - cbr) * k | 0;
  9516. bytes[j++] = cag - (cag - cbg) * k | 0;
  9517. bytes[j++] = cab - (cab - cbb) * k | 0;
  9518. bytes[j++] = 255;
  9519. }
  9520. }
  9521. }
  9522. function drawFigure(data, figure, context) {
  9523. const ps = figure.coords;
  9524. const cs = figure.colors;
  9525. let i, ii;
  9526. switch (figure.type) {
  9527. case "lattice":
  9528. const verticesPerRow = figure.verticesPerRow;
  9529. const rows = Math.floor(ps.length / verticesPerRow) - 1;
  9530. const cols = verticesPerRow - 1;
  9531. for (i = 0; i < rows; i++) {
  9532. let q = i * verticesPerRow;
  9533. for (let j = 0; j < cols; j++, q++) {
  9534. drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
  9535. drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  9536. }
  9537. }
  9538. break;
  9539. case "triangles":
  9540. for (i = 0, ii = ps.length; i < ii; i += 3) {
  9541. drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
  9542. }
  9543. break;
  9544. default:
  9545. throw new Error("illegal figure");
  9546. }
  9547. }
  9548. class MeshShadingPattern extends BaseShadingPattern {
  9549. constructor(IR) {
  9550. super();
  9551. this._coords = IR[2];
  9552. this._colors = IR[3];
  9553. this._figures = IR[4];
  9554. this._bounds = IR[5];
  9555. this._bbox = IR[7];
  9556. this._background = IR[8];
  9557. this.matrix = null;
  9558. }
  9559. _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
  9560. const EXPECTED_SCALE = 1.1;
  9561. const MAX_PATTERN_SIZE = 3000;
  9562. const BORDER_SIZE = 2;
  9563. const offsetX = Math.floor(this._bounds[0]);
  9564. const offsetY = Math.floor(this._bounds[1]);
  9565. const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
  9566. const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
  9567. const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  9568. const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  9569. const scaleX = boundsWidth / width;
  9570. const scaleY = boundsHeight / height;
  9571. const context = {
  9572. coords: this._coords,
  9573. colors: this._colors,
  9574. offsetX: -offsetX,
  9575. offsetY: -offsetY,
  9576. scaleX: 1 / scaleX,
  9577. scaleY: 1 / scaleY
  9578. };
  9579. const paddedWidth = width + BORDER_SIZE * 2;
  9580. const paddedHeight = height + BORDER_SIZE * 2;
  9581. const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight);
  9582. const tmpCtx = tmpCanvas.context;
  9583. const data = tmpCtx.createImageData(width, height);
  9584. if (backgroundColor) {
  9585. const bytes = data.data;
  9586. for (let i = 0, ii = bytes.length; i < ii; i += 4) {
  9587. bytes[i] = backgroundColor[0];
  9588. bytes[i + 1] = backgroundColor[1];
  9589. bytes[i + 2] = backgroundColor[2];
  9590. bytes[i + 3] = 255;
  9591. }
  9592. }
  9593. for (const figure of this._figures) {
  9594. drawFigure(data, figure, context);
  9595. }
  9596. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  9597. const canvas = tmpCanvas.canvas;
  9598. return {
  9599. canvas,
  9600. offsetX: offsetX - BORDER_SIZE * scaleX,
  9601. offsetY: offsetY - BORDER_SIZE * scaleY,
  9602. scaleX,
  9603. scaleY
  9604. };
  9605. }
  9606. getPattern(ctx, owner, inverse, pathType) {
  9607. applyBoundingBox(ctx, this._bbox);
  9608. let scale;
  9609. if (pathType === PathType.SHADING) {
  9610. scale = Util.singularValueDecompose2dScale(getCurrentTransform(ctx));
  9611. } else {
  9612. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  9613. if (this.matrix) {
  9614. const matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  9615. scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
  9616. }
  9617. }
  9618. const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);
  9619. if (pathType !== PathType.SHADING) {
  9620. ctx.setTransform(...owner.baseTransform);
  9621. if (this.matrix) {
  9622. ctx.transform(...this.matrix);
  9623. }
  9624. }
  9625. ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  9626. ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
  9627. return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
  9628. }
  9629. }
  9630. class DummyShadingPattern extends BaseShadingPattern {
  9631. getPattern() {
  9632. return "hotpink";
  9633. }
  9634. }
  9635. function getShadingPattern(IR) {
  9636. switch (IR[0]) {
  9637. case "RadialAxial":
  9638. return new RadialAxialShadingPattern(IR);
  9639. case "Mesh":
  9640. return new MeshShadingPattern(IR);
  9641. case "Dummy":
  9642. return new DummyShadingPattern();
  9643. }
  9644. throw new Error(`Unknown IR type: ${IR[0]}`);
  9645. }
  9646. const PaintType = {
  9647. COLORED: 1,
  9648. UNCOLORED: 2
  9649. };
  9650. class TilingPattern {
  9651. static MAX_PATTERN_SIZE = 3000;
  9652. constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  9653. this.operatorList = IR[2];
  9654. this.matrix = IR[3];
  9655. this.bbox = IR[4];
  9656. this.xstep = IR[5];
  9657. this.ystep = IR[6];
  9658. this.paintType = IR[7];
  9659. this.tilingType = IR[8];
  9660. this.color = color;
  9661. this.ctx = ctx;
  9662. this.canvasGraphicsFactory = canvasGraphicsFactory;
  9663. this.baseTransform = baseTransform;
  9664. }
  9665. createPatternCanvas(owner) {
  9666. const {
  9667. bbox,
  9668. operatorList,
  9669. paintType,
  9670. tilingType,
  9671. color,
  9672. canvasGraphicsFactory
  9673. } = this;
  9674. let {
  9675. xstep,
  9676. ystep
  9677. } = this;
  9678. xstep = Math.abs(xstep);
  9679. ystep = Math.abs(ystep);
  9680. info("TilingType: " + tilingType);
  9681. const x0 = bbox[0],
  9682. y0 = bbox[1],
  9683. x1 = bbox[2],
  9684. y1 = bbox[3];
  9685. const width = x1 - x0;
  9686. const height = y1 - y0;
  9687. const matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  9688. const curMatrixScale = Util.singularValueDecompose2dScale(this.baseTransform);
  9689. const combinedScaleX = matrixScale[0] * curMatrixScale[0];
  9690. const combinedScaleY = matrixScale[1] * curMatrixScale[1];
  9691. let canvasWidth = width,
  9692. canvasHeight = height,
  9693. redrawHorizontally = false,
  9694. redrawVertically = false;
  9695. const xScaledStep = Math.ceil(xstep * combinedScaleX);
  9696. const yScaledStep = Math.ceil(ystep * combinedScaleY);
  9697. const xScaledWidth = Math.ceil(width * combinedScaleX);
  9698. const yScaledHeight = Math.ceil(height * combinedScaleY);
  9699. if (xScaledStep >= xScaledWidth) {
  9700. canvasWidth = xstep;
  9701. } else {
  9702. redrawHorizontally = true;
  9703. }
  9704. if (yScaledStep >= yScaledHeight) {
  9705. canvasHeight = ystep;
  9706. } else {
  9707. redrawVertically = true;
  9708. }
  9709. const dimx = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX);
  9710. const dimy = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY);
  9711. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size);
  9712. const tmpCtx = tmpCanvas.context;
  9713. const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  9714. graphics.groupLevel = owner.groupLevel;
  9715. this.setFillAndStrokeStyleToContext(graphics, paintType, color);
  9716. tmpCtx.translate(-dimx.scale * x0, -dimy.scale * y0);
  9717. graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
  9718. tmpCtx.save();
  9719. this.clipBbox(graphics, x0, y0, x1, y1);
  9720. graphics.baseTransform = getCurrentTransform(graphics.ctx);
  9721. graphics.executeOperatorList(operatorList);
  9722. graphics.endDrawing();
  9723. tmpCtx.restore();
  9724. if (redrawHorizontally || redrawVertically) {
  9725. const image = tmpCanvas.canvas;
  9726. if (redrawHorizontally) {
  9727. canvasWidth = xstep;
  9728. }
  9729. if (redrawVertically) {
  9730. canvasHeight = ystep;
  9731. }
  9732. const dimx2 = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX);
  9733. const dimy2 = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY);
  9734. const xSize = dimx2.size;
  9735. const ySize = dimy2.size;
  9736. const tmpCanvas2 = owner.cachedCanvases.getCanvas("pattern-workaround", xSize, ySize);
  9737. const tmpCtx2 = tmpCanvas2.context;
  9738. const ii = redrawHorizontally ? Math.floor(width / xstep) : 0;
  9739. const jj = redrawVertically ? Math.floor(height / ystep) : 0;
  9740. for (let i = 0; i <= ii; i++) {
  9741. for (let j = 0; j <= jj; j++) {
  9742. tmpCtx2.drawImage(image, xSize * i, ySize * j, xSize, ySize, 0, 0, xSize, ySize);
  9743. }
  9744. }
  9745. return {
  9746. canvas: tmpCanvas2.canvas,
  9747. scaleX: dimx2.scale,
  9748. scaleY: dimy2.scale,
  9749. offsetX: x0,
  9750. offsetY: y0
  9751. };
  9752. }
  9753. return {
  9754. canvas: tmpCanvas.canvas,
  9755. scaleX: dimx.scale,
  9756. scaleY: dimy.scale,
  9757. offsetX: x0,
  9758. offsetY: y0
  9759. };
  9760. }
  9761. getSizeAndScale(step, realOutputSize, scale) {
  9762. const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
  9763. let size = Math.ceil(step * scale);
  9764. if (size >= maxSize) {
  9765. size = maxSize;
  9766. } else {
  9767. scale = size / step;
  9768. }
  9769. return {
  9770. scale,
  9771. size
  9772. };
  9773. }
  9774. clipBbox(graphics, x0, y0, x1, y1) {
  9775. const bboxWidth = x1 - x0;
  9776. const bboxHeight = y1 - y0;
  9777. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  9778. graphics.current.updateRectMinMax(getCurrentTransform(graphics.ctx), [x0, y0, x1, y1]);
  9779. graphics.clip();
  9780. graphics.endPath();
  9781. }
  9782. setFillAndStrokeStyleToContext(graphics, paintType, color) {
  9783. const context = graphics.ctx,
  9784. current = graphics.current;
  9785. switch (paintType) {
  9786. case PaintType.COLORED:
  9787. const ctx = this.ctx;
  9788. context.fillStyle = ctx.fillStyle;
  9789. context.strokeStyle = ctx.strokeStyle;
  9790. current.fillColor = ctx.fillStyle;
  9791. current.strokeColor = ctx.strokeStyle;
  9792. break;
  9793. case PaintType.UNCOLORED:
  9794. const cssColor = Util.makeHexColor(color[0], color[1], color[2]);
  9795. context.fillStyle = cssColor;
  9796. context.strokeStyle = cssColor;
  9797. current.fillColor = cssColor;
  9798. current.strokeColor = cssColor;
  9799. break;
  9800. default:
  9801. throw new FormatError(`Unsupported paint type: ${paintType}`);
  9802. }
  9803. }
  9804. getPattern(ctx, owner, inverse, pathType) {
  9805. let matrix = inverse;
  9806. if (pathType !== PathType.SHADING) {
  9807. matrix = Util.transform(matrix, owner.baseTransform);
  9808. if (this.matrix) {
  9809. matrix = Util.transform(matrix, this.matrix);
  9810. }
  9811. }
  9812. const temporaryPatternCanvas = this.createPatternCanvas(owner);
  9813. let domMatrix = new DOMMatrix(matrix);
  9814. domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  9815. domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
  9816. const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
  9817. pattern.setTransform(domMatrix);
  9818. return pattern;
  9819. }
  9820. }
  9821. ;// ./src/shared/image_utils.js
  9822. function convertToRGBA(params) {
  9823. switch (params.kind) {
  9824. case ImageKind.GRAYSCALE_1BPP:
  9825. return convertBlackAndWhiteToRGBA(params);
  9826. case ImageKind.RGB_24BPP:
  9827. return convertRGBToRGBA(params);
  9828. }
  9829. return null;
  9830. }
  9831. function convertBlackAndWhiteToRGBA({
  9832. src,
  9833. srcPos = 0,
  9834. dest,
  9835. width,
  9836. height,
  9837. nonBlackColor = 0xffffffff,
  9838. inverseDecode = false
  9839. }) {
  9840. const black = util_FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  9841. const [zeroMapping, oneMapping] = inverseDecode ? [nonBlackColor, black] : [black, nonBlackColor];
  9842. const widthInSource = width >> 3;
  9843. const widthRemainder = width & 7;
  9844. const srcLength = src.length;
  9845. dest = new Uint32Array(dest.buffer);
  9846. let destPos = 0;
  9847. for (let i = 0; i < height; i++) {
  9848. for (const max = srcPos + widthInSource; srcPos < max; srcPos++) {
  9849. const elem = srcPos < srcLength ? src[srcPos] : 255;
  9850. dest[destPos++] = elem & 0b10000000 ? oneMapping : zeroMapping;
  9851. dest[destPos++] = elem & 0b1000000 ? oneMapping : zeroMapping;
  9852. dest[destPos++] = elem & 0b100000 ? oneMapping : zeroMapping;
  9853. dest[destPos++] = elem & 0b10000 ? oneMapping : zeroMapping;
  9854. dest[destPos++] = elem & 0b1000 ? oneMapping : zeroMapping;
  9855. dest[destPos++] = elem & 0b100 ? oneMapping : zeroMapping;
  9856. dest[destPos++] = elem & 0b10 ? oneMapping : zeroMapping;
  9857. dest[destPos++] = elem & 0b1 ? oneMapping : zeroMapping;
  9858. }
  9859. if (widthRemainder === 0) {
  9860. continue;
  9861. }
  9862. const elem = srcPos < srcLength ? src[srcPos++] : 255;
  9863. for (let j = 0; j < widthRemainder; j++) {
  9864. dest[destPos++] = elem & 1 << 7 - j ? oneMapping : zeroMapping;
  9865. }
  9866. }
  9867. return {
  9868. srcPos,
  9869. destPos
  9870. };
  9871. }
  9872. function convertRGBToRGBA({
  9873. src,
  9874. srcPos = 0,
  9875. dest,
  9876. destPos = 0,
  9877. width,
  9878. height
  9879. }) {
  9880. let i = 0;
  9881. const len32 = src.length >> 2;
  9882. const src32 = new Uint32Array(src.buffer, srcPos, len32);
  9883. if (FeatureTest.isLittleEndian) {
  9884. for (; i < len32 - 2; i += 3, destPos += 4) {
  9885. const s1 = src32[i];
  9886. const s2 = src32[i + 1];
  9887. const s3 = src32[i + 2];
  9888. dest[destPos] = s1 | 0xff000000;
  9889. dest[destPos + 1] = s1 >>> 24 | s2 << 8 | 0xff000000;
  9890. dest[destPos + 2] = s2 >>> 16 | s3 << 16 | 0xff000000;
  9891. dest[destPos + 3] = s3 >>> 8 | 0xff000000;
  9892. }
  9893. for (let j = i * 4, jj = src.length; j < jj; j += 3) {
  9894. dest[destPos++] = src[j] | src[j + 1] << 8 | src[j + 2] << 16 | 0xff000000;
  9895. }
  9896. } else {
  9897. for (; i < len32 - 2; i += 3, destPos += 4) {
  9898. const s1 = src32[i];
  9899. const s2 = src32[i + 1];
  9900. const s3 = src32[i + 2];
  9901. dest[destPos] = s1 | 0xff;
  9902. dest[destPos + 1] = s1 << 24 | s2 >>> 8 | 0xff;
  9903. dest[destPos + 2] = s2 << 16 | s3 >>> 16 | 0xff;
  9904. dest[destPos + 3] = s3 << 8 | 0xff;
  9905. }
  9906. for (let j = i * 4, jj = src.length; j < jj; j += 3) {
  9907. dest[destPos++] = src[j] << 24 | src[j + 1] << 16 | src[j + 2] << 8 | 0xff;
  9908. }
  9909. }
  9910. return {
  9911. srcPos,
  9912. destPos
  9913. };
  9914. }
  9915. function grayToRGBA(src, dest) {
  9916. if (FeatureTest.isLittleEndian) {
  9917. for (let i = 0, ii = src.length; i < ii; i++) {
  9918. dest[i] = src[i] * 0x10101 | 0xff000000;
  9919. }
  9920. } else {
  9921. for (let i = 0, ii = src.length; i < ii; i++) {
  9922. dest[i] = src[i] * 0x1010100 | 0x000000ff;
  9923. }
  9924. }
  9925. }
  9926. ;// ./src/display/canvas.js
  9927. const MIN_FONT_SIZE = 16;
  9928. const MAX_FONT_SIZE = 100;
  9929. const EXECUTION_TIME = 15;
  9930. const EXECUTION_STEPS = 10;
  9931. const MAX_SIZE_TO_COMPILE = 1000;
  9932. const FULL_CHUNK_HEIGHT = 16;
  9933. function mirrorContextOperations(ctx, destCtx) {
  9934. if (ctx._removeMirroring) {
  9935. throw new Error("Context is already forwarding operations.");
  9936. }
  9937. ctx.__originalSave = ctx.save;
  9938. ctx.__originalRestore = ctx.restore;
  9939. ctx.__originalRotate = ctx.rotate;
  9940. ctx.__originalScale = ctx.scale;
  9941. ctx.__originalTranslate = ctx.translate;
  9942. ctx.__originalTransform = ctx.transform;
  9943. ctx.__originalSetTransform = ctx.setTransform;
  9944. ctx.__originalResetTransform = ctx.resetTransform;
  9945. ctx.__originalClip = ctx.clip;
  9946. ctx.__originalMoveTo = ctx.moveTo;
  9947. ctx.__originalLineTo = ctx.lineTo;
  9948. ctx.__originalBezierCurveTo = ctx.bezierCurveTo;
  9949. ctx.__originalRect = ctx.rect;
  9950. ctx.__originalClosePath = ctx.closePath;
  9951. ctx.__originalBeginPath = ctx.beginPath;
  9952. ctx._removeMirroring = () => {
  9953. ctx.save = ctx.__originalSave;
  9954. ctx.restore = ctx.__originalRestore;
  9955. ctx.rotate = ctx.__originalRotate;
  9956. ctx.scale = ctx.__originalScale;
  9957. ctx.translate = ctx.__originalTranslate;
  9958. ctx.transform = ctx.__originalTransform;
  9959. ctx.setTransform = ctx.__originalSetTransform;
  9960. ctx.resetTransform = ctx.__originalResetTransform;
  9961. ctx.clip = ctx.__originalClip;
  9962. ctx.moveTo = ctx.__originalMoveTo;
  9963. ctx.lineTo = ctx.__originalLineTo;
  9964. ctx.bezierCurveTo = ctx.__originalBezierCurveTo;
  9965. ctx.rect = ctx.__originalRect;
  9966. ctx.closePath = ctx.__originalClosePath;
  9967. ctx.beginPath = ctx.__originalBeginPath;
  9968. delete ctx._removeMirroring;
  9969. };
  9970. ctx.save = function ctxSave() {
  9971. destCtx.save();
  9972. this.__originalSave();
  9973. };
  9974. ctx.restore = function ctxRestore() {
  9975. destCtx.restore();
  9976. this.__originalRestore();
  9977. };
  9978. ctx.translate = function ctxTranslate(x, y) {
  9979. destCtx.translate(x, y);
  9980. this.__originalTranslate(x, y);
  9981. };
  9982. ctx.scale = function ctxScale(x, y) {
  9983. destCtx.scale(x, y);
  9984. this.__originalScale(x, y);
  9985. };
  9986. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  9987. destCtx.transform(a, b, c, d, e, f);
  9988. this.__originalTransform(a, b, c, d, e, f);
  9989. };
  9990. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  9991. destCtx.setTransform(a, b, c, d, e, f);
  9992. this.__originalSetTransform(a, b, c, d, e, f);
  9993. };
  9994. ctx.resetTransform = function ctxResetTransform() {
  9995. destCtx.resetTransform();
  9996. this.__originalResetTransform();
  9997. };
  9998. ctx.rotate = function ctxRotate(angle) {
  9999. destCtx.rotate(angle);
  10000. this.__originalRotate(angle);
  10001. };
  10002. ctx.clip = function ctxRotate(rule) {
  10003. destCtx.clip(rule);
  10004. this.__originalClip(rule);
  10005. };
  10006. ctx.moveTo = function (x, y) {
  10007. destCtx.moveTo(x, y);
  10008. this.__originalMoveTo(x, y);
  10009. };
  10010. ctx.lineTo = function (x, y) {
  10011. destCtx.lineTo(x, y);
  10012. this.__originalLineTo(x, y);
  10013. };
  10014. ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {
  10015. destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  10016. this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  10017. };
  10018. ctx.rect = function (x, y, width, height) {
  10019. destCtx.rect(x, y, width, height);
  10020. this.__originalRect(x, y, width, height);
  10021. };
  10022. ctx.closePath = function () {
  10023. destCtx.closePath();
  10024. this.__originalClosePath();
  10025. };
  10026. ctx.beginPath = function () {
  10027. destCtx.beginPath();
  10028. this.__originalBeginPath();
  10029. };
  10030. }
  10031. class CachedCanvases {
  10032. constructor(canvasFactory) {
  10033. this.canvasFactory = canvasFactory;
  10034. this.cache = Object.create(null);
  10035. }
  10036. getCanvas(id, width, height) {
  10037. let canvasEntry;
  10038. if (this.cache[id] !== undefined) {
  10039. canvasEntry = this.cache[id];
  10040. this.canvasFactory.reset(canvasEntry, width, height);
  10041. } else {
  10042. canvasEntry = this.canvasFactory.create(width, height);
  10043. this.cache[id] = canvasEntry;
  10044. }
  10045. return canvasEntry;
  10046. }
  10047. delete(id) {
  10048. delete this.cache[id];
  10049. }
  10050. clear() {
  10051. for (const id in this.cache) {
  10052. const canvasEntry = this.cache[id];
  10053. this.canvasFactory.destroy(canvasEntry);
  10054. delete this.cache[id];
  10055. }
  10056. }
  10057. }
  10058. function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) {
  10059. const [a, b, c, d, tx, ty] = getCurrentTransform(ctx);
  10060. if (b === 0 && c === 0) {
  10061. const tlX = destX * a + tx;
  10062. const rTlX = Math.round(tlX);
  10063. const tlY = destY * d + ty;
  10064. const rTlY = Math.round(tlY);
  10065. const brX = (destX + destW) * a + tx;
  10066. const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
  10067. const brY = (destY + destH) * d + ty;
  10068. const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
  10069. ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY);
  10070. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight);
  10071. ctx.setTransform(a, b, c, d, tx, ty);
  10072. return [rWidth, rHeight];
  10073. }
  10074. if (a === 0 && d === 0) {
  10075. const tlX = destY * c + tx;
  10076. const rTlX = Math.round(tlX);
  10077. const tlY = destX * b + ty;
  10078. const rTlY = Math.round(tlY);
  10079. const brX = (destY + destH) * c + tx;
  10080. const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
  10081. const brY = (destX + destW) * b + ty;
  10082. const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
  10083. ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY);
  10084. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth);
  10085. ctx.setTransform(a, b, c, d, tx, ty);
  10086. return [rHeight, rWidth];
  10087. }
  10088. ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH);
  10089. const scaleX = Math.hypot(a, b);
  10090. const scaleY = Math.hypot(c, d);
  10091. return [scaleX * destW, scaleY * destH];
  10092. }
  10093. function compileType3Glyph(imgData) {
  10094. const {
  10095. width,
  10096. height
  10097. } = imgData;
  10098. if (width > MAX_SIZE_TO_COMPILE || height > MAX_SIZE_TO_COMPILE) {
  10099. return null;
  10100. }
  10101. const POINT_TO_PROCESS_LIMIT = 1000;
  10102. const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  10103. const width1 = width + 1;
  10104. let points = new Uint8Array(width1 * (height + 1));
  10105. let i, j, j0;
  10106. const lineSize = width + 7 & ~7;
  10107. let data = new Uint8Array(lineSize * height),
  10108. pos = 0;
  10109. for (const elem of imgData.data) {
  10110. let mask = 128;
  10111. while (mask > 0) {
  10112. data[pos++] = elem & mask ? 0 : 255;
  10113. mask >>= 1;
  10114. }
  10115. }
  10116. let count = 0;
  10117. pos = 0;
  10118. if (data[pos] !== 0) {
  10119. points[0] = 1;
  10120. ++count;
  10121. }
  10122. for (j = 1; j < width; j++) {
  10123. if (data[pos] !== data[pos + 1]) {
  10124. points[j] = data[pos] ? 2 : 1;
  10125. ++count;
  10126. }
  10127. pos++;
  10128. }
  10129. if (data[pos] !== 0) {
  10130. points[j] = 2;
  10131. ++count;
  10132. }
  10133. for (i = 1; i < height; i++) {
  10134. pos = i * lineSize;
  10135. j0 = i * width1;
  10136. if (data[pos - lineSize] !== data[pos]) {
  10137. points[j0] = data[pos] ? 1 : 8;
  10138. ++count;
  10139. }
  10140. let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  10141. for (j = 1; j < width; j++) {
  10142. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
  10143. if (POINT_TYPES[sum]) {
  10144. points[j0 + j] = POINT_TYPES[sum];
  10145. ++count;
  10146. }
  10147. pos++;
  10148. }
  10149. if (data[pos - lineSize] !== data[pos]) {
  10150. points[j0 + j] = data[pos] ? 2 : 4;
  10151. ++count;
  10152. }
  10153. if (count > POINT_TO_PROCESS_LIMIT) {
  10154. return null;
  10155. }
  10156. }
  10157. pos = lineSize * (height - 1);
  10158. j0 = i * width1;
  10159. if (data[pos] !== 0) {
  10160. points[j0] = 8;
  10161. ++count;
  10162. }
  10163. for (j = 1; j < width; j++) {
  10164. if (data[pos] !== data[pos + 1]) {
  10165. points[j0 + j] = data[pos] ? 4 : 8;
  10166. ++count;
  10167. }
  10168. pos++;
  10169. }
  10170. if (data[pos] !== 0) {
  10171. points[j0 + j] = 4;
  10172. ++count;
  10173. }
  10174. if (count > POINT_TO_PROCESS_LIMIT) {
  10175. return null;
  10176. }
  10177. const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  10178. const path = new Path2D();
  10179. for (i = 0; count && i <= height; i++) {
  10180. let p = i * width1;
  10181. const end = p + width;
  10182. while (p < end && !points[p]) {
  10183. p++;
  10184. }
  10185. if (p === end) {
  10186. continue;
  10187. }
  10188. path.moveTo(p % width1, i);
  10189. const p0 = p;
  10190. let type = points[p];
  10191. do {
  10192. const step = steps[type];
  10193. do {
  10194. p += step;
  10195. } while (!points[p]);
  10196. const pp = points[p];
  10197. if (pp !== 5 && pp !== 10) {
  10198. type = pp;
  10199. points[p] = 0;
  10200. } else {
  10201. type = pp & 0x33 * type >> 4;
  10202. points[p] &= type >> 2 | type << 2;
  10203. }
  10204. path.lineTo(p % width1, p / width1 | 0);
  10205. if (!points[p]) {
  10206. --count;
  10207. }
  10208. } while (p0 !== p);
  10209. --i;
  10210. }
  10211. data = null;
  10212. points = null;
  10213. const drawOutline = function (c) {
  10214. c.save();
  10215. c.scale(1 / width, -1 / height);
  10216. c.translate(0, -height);
  10217. c.fill(path);
  10218. c.beginPath();
  10219. c.restore();
  10220. };
  10221. return drawOutline;
  10222. }
  10223. class CanvasExtraState {
  10224. constructor(width, height) {
  10225. this.alphaIsShape = false;
  10226. this.fontSize = 0;
  10227. this.fontSizeScale = 1;
  10228. this.textMatrix = IDENTITY_MATRIX;
  10229. this.textMatrixScale = 1;
  10230. this.fontMatrix = FONT_IDENTITY_MATRIX;
  10231. this.leading = 0;
  10232. this.x = 0;
  10233. this.y = 0;
  10234. this.lineX = 0;
  10235. this.lineY = 0;
  10236. this.charSpacing = 0;
  10237. this.wordSpacing = 0;
  10238. this.textHScale = 1;
  10239. this.textRenderingMode = TextRenderingMode.FILL;
  10240. this.textRise = 0;
  10241. this.fillColor = "#000000";
  10242. this.strokeColor = "#000000";
  10243. this.patternFill = false;
  10244. this.fillAlpha = 1;
  10245. this.strokeAlpha = 1;
  10246. this.lineWidth = 1;
  10247. this.activeSMask = null;
  10248. this.transferMaps = "none";
  10249. this.startNewPathAndClipBox([0, 0, width, height]);
  10250. }
  10251. clone() {
  10252. const clone = Object.create(this);
  10253. clone.clipBox = this.clipBox.slice();
  10254. return clone;
  10255. }
  10256. setCurrentPoint(x, y) {
  10257. this.x = x;
  10258. this.y = y;
  10259. }
  10260. updatePathMinMax(transform, x, y) {
  10261. [x, y] = Util.applyTransform([x, y], transform);
  10262. this.minX = Math.min(this.minX, x);
  10263. this.minY = Math.min(this.minY, y);
  10264. this.maxX = Math.max(this.maxX, x);
  10265. this.maxY = Math.max(this.maxY, y);
  10266. }
  10267. updateRectMinMax(transform, rect) {
  10268. const p1 = Util.applyTransform(rect, transform);
  10269. const p2 = Util.applyTransform(rect.slice(2), transform);
  10270. const p3 = Util.applyTransform([rect[0], rect[3]], transform);
  10271. const p4 = Util.applyTransform([rect[2], rect[1]], transform);
  10272. this.minX = Math.min(this.minX, p1[0], p2[0], p3[0], p4[0]);
  10273. this.minY = Math.min(this.minY, p1[1], p2[1], p3[1], p4[1]);
  10274. this.maxX = Math.max(this.maxX, p1[0], p2[0], p3[0], p4[0]);
  10275. this.maxY = Math.max(this.maxY, p1[1], p2[1], p3[1], p4[1]);
  10276. }
  10277. updateScalingPathMinMax(transform, minMax) {
  10278. Util.scaleMinMax(transform, minMax);
  10279. this.minX = Math.min(this.minX, minMax[0]);
  10280. this.minY = Math.min(this.minY, minMax[1]);
  10281. this.maxX = Math.max(this.maxX, minMax[2]);
  10282. this.maxY = Math.max(this.maxY, minMax[3]);
  10283. }
  10284. updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
  10285. const box = Util.bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3, minMax);
  10286. if (minMax) {
  10287. return;
  10288. }
  10289. this.updateRectMinMax(transform, box);
  10290. }
  10291. getPathBoundingBox(pathType = PathType.FILL, transform = null) {
  10292. const box = [this.minX, this.minY, this.maxX, this.maxY];
  10293. if (pathType === PathType.STROKE) {
  10294. if (!transform) {
  10295. unreachable("Stroke bounding box must include transform.");
  10296. }
  10297. const scale = Util.singularValueDecompose2dScale(transform);
  10298. const xStrokePad = scale[0] * this.lineWidth / 2;
  10299. const yStrokePad = scale[1] * this.lineWidth / 2;
  10300. box[0] -= xStrokePad;
  10301. box[1] -= yStrokePad;
  10302. box[2] += xStrokePad;
  10303. box[3] += yStrokePad;
  10304. }
  10305. return box;
  10306. }
  10307. updateClipFromPath() {
  10308. const intersect = Util.intersect(this.clipBox, this.getPathBoundingBox());
  10309. this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);
  10310. }
  10311. isEmptyClip() {
  10312. return this.minX === Infinity;
  10313. }
  10314. startNewPathAndClipBox(box) {
  10315. this.clipBox = box;
  10316. this.minX = Infinity;
  10317. this.minY = Infinity;
  10318. this.maxX = 0;
  10319. this.maxY = 0;
  10320. }
  10321. getClippedPathBoundingBox(pathType = PathType.FILL, transform = null) {
  10322. return Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform));
  10323. }
  10324. }
  10325. function putBinaryImageData(ctx, imgData) {
  10326. if (typeof ImageData !== "undefined" && imgData instanceof ImageData) {
  10327. ctx.putImageData(imgData, 0, 0);
  10328. return;
  10329. }
  10330. const height = imgData.height,
  10331. width = imgData.width;
  10332. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  10333. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  10334. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  10335. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  10336. let srcPos = 0,
  10337. destPos;
  10338. const src = imgData.data;
  10339. const dest = chunkImgData.data;
  10340. let i, j, thisChunkHeight, elemsInThisChunk;
  10341. if (imgData.kind === util_ImageKind.GRAYSCALE_1BPP) {
  10342. const srcLength = src.byteLength;
  10343. const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
  10344. const dest32DataLength = dest32.length;
  10345. const fullSrcDiff = width + 7 >> 3;
  10346. const white = 0xffffffff;
  10347. const black = util_FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  10348. for (i = 0; i < totalChunks; i++) {
  10349. thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  10350. destPos = 0;
  10351. for (j = 0; j < thisChunkHeight; j++) {
  10352. const srcDiff = srcLength - srcPos;
  10353. let k = 0;
  10354. const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
  10355. const kEndUnrolled = kEnd & ~7;
  10356. let mask = 0;
  10357. let srcByte = 0;
  10358. for (; k < kEndUnrolled; k += 8) {
  10359. srcByte = src[srcPos++];
  10360. dest32[destPos++] = srcByte & 128 ? white : black;
  10361. dest32[destPos++] = srcByte & 64 ? white : black;
  10362. dest32[destPos++] = srcByte & 32 ? white : black;
  10363. dest32[destPos++] = srcByte & 16 ? white : black;
  10364. dest32[destPos++] = srcByte & 8 ? white : black;
  10365. dest32[destPos++] = srcByte & 4 ? white : black;
  10366. dest32[destPos++] = srcByte & 2 ? white : black;
  10367. dest32[destPos++] = srcByte & 1 ? white : black;
  10368. }
  10369. for (; k < kEnd; k++) {
  10370. if (mask === 0) {
  10371. srcByte = src[srcPos++];
  10372. mask = 128;
  10373. }
  10374. dest32[destPos++] = srcByte & mask ? white : black;
  10375. mask >>= 1;
  10376. }
  10377. }
  10378. while (destPos < dest32DataLength) {
  10379. dest32[destPos++] = 0;
  10380. }
  10381. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  10382. }
  10383. } else if (imgData.kind === util_ImageKind.RGBA_32BPP) {
  10384. j = 0;
  10385. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  10386. for (i = 0; i < fullChunks; i++) {
  10387. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  10388. srcPos += elemsInThisChunk;
  10389. ctx.putImageData(chunkImgData, 0, j);
  10390. j += FULL_CHUNK_HEIGHT;
  10391. }
  10392. if (i < totalChunks) {
  10393. elemsInThisChunk = width * partialChunkHeight * 4;
  10394. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  10395. ctx.putImageData(chunkImgData, 0, j);
  10396. }
  10397. } else if (imgData.kind === util_ImageKind.RGB_24BPP) {
  10398. thisChunkHeight = FULL_CHUNK_HEIGHT;
  10399. elemsInThisChunk = width * thisChunkHeight;
  10400. for (i = 0; i < totalChunks; i++) {
  10401. if (i >= fullChunks) {
  10402. thisChunkHeight = partialChunkHeight;
  10403. elemsInThisChunk = width * thisChunkHeight;
  10404. }
  10405. destPos = 0;
  10406. for (j = elemsInThisChunk; j--;) {
  10407. dest[destPos++] = src[srcPos++];
  10408. dest[destPos++] = src[srcPos++];
  10409. dest[destPos++] = src[srcPos++];
  10410. dest[destPos++] = 255;
  10411. }
  10412. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  10413. }
  10414. } else {
  10415. throw new Error(`bad image kind: ${imgData.kind}`);
  10416. }
  10417. }
  10418. function putBinaryImageMask(ctx, imgData) {
  10419. if (imgData.bitmap) {
  10420. ctx.drawImage(imgData.bitmap, 0, 0);
  10421. return;
  10422. }
  10423. const height = imgData.height,
  10424. width = imgData.width;
  10425. const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  10426. const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  10427. const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  10428. const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  10429. let srcPos = 0;
  10430. const src = imgData.data;
  10431. const dest = chunkImgData.data;
  10432. for (let i = 0; i < totalChunks; i++) {
  10433. const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  10434. ({
  10435. srcPos
  10436. } = convertBlackAndWhiteToRGBA({
  10437. src,
  10438. srcPos,
  10439. dest,
  10440. width,
  10441. height: thisChunkHeight,
  10442. nonBlackColor: 0
  10443. }));
  10444. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  10445. }
  10446. }
  10447. function copyCtxState(sourceCtx, destCtx) {
  10448. const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font", "filter"];
  10449. for (const property of properties) {
  10450. if (sourceCtx[property] !== undefined) {
  10451. destCtx[property] = sourceCtx[property];
  10452. }
  10453. }
  10454. if (sourceCtx.setLineDash !== undefined) {
  10455. destCtx.setLineDash(sourceCtx.getLineDash());
  10456. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  10457. }
  10458. }
  10459. function resetCtxToDefault(ctx) {
  10460. ctx.strokeStyle = ctx.fillStyle = "#000000";
  10461. ctx.fillRule = "nonzero";
  10462. ctx.globalAlpha = 1;
  10463. ctx.lineWidth = 1;
  10464. ctx.lineCap = "butt";
  10465. ctx.lineJoin = "miter";
  10466. ctx.miterLimit = 10;
  10467. ctx.globalCompositeOperation = "source-over";
  10468. ctx.font = "10px sans-serif";
  10469. if (ctx.setLineDash !== undefined) {
  10470. ctx.setLineDash([]);
  10471. ctx.lineDashOffset = 0;
  10472. }
  10473. if (!isNodeJS) {
  10474. const {
  10475. filter
  10476. } = ctx;
  10477. if (filter !== "none" && filter !== "") {
  10478. ctx.filter = "none";
  10479. }
  10480. }
  10481. }
  10482. function getImageSmoothingEnabled(transform, interpolate) {
  10483. if (interpolate) {
  10484. return true;
  10485. }
  10486. const scale = Util.singularValueDecompose2dScale(transform);
  10487. scale[0] = Math.fround(scale[0]);
  10488. scale[1] = Math.fround(scale[1]);
  10489. const actualScale = Math.fround((globalThis.devicePixelRatio || 1) * PixelsPerInch.PDF_TO_CSS_UNITS);
  10490. return scale[0] <= actualScale && scale[1] <= actualScale;
  10491. }
  10492. const LINE_CAP_STYLES = ["butt", "round", "square"];
  10493. const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  10494. const NORMAL_CLIP = {};
  10495. const EO_CLIP = {};
  10496. class CanvasGraphics {
  10497. constructor(canvasCtx, commonObjs, objs, canvasFactory, filterFactory, {
  10498. optionalContentConfig,
  10499. markedContentStack = null
  10500. }, annotationCanvasMap, pageColors) {
  10501. this.ctx = canvasCtx;
  10502. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  10503. this.stateStack = [];
  10504. this.pendingClip = null;
  10505. this.pendingEOFill = false;
  10506. this.res = null;
  10507. this.xobjs = null;
  10508. this.commonObjs = commonObjs;
  10509. this.objs = objs;
  10510. this.canvasFactory = canvasFactory;
  10511. this.filterFactory = filterFactory;
  10512. this.groupStack = [];
  10513. this.processingType3 = null;
  10514. this.baseTransform = null;
  10515. this.baseTransformStack = [];
  10516. this.groupLevel = 0;
  10517. this.smaskStack = [];
  10518. this.smaskCounter = 0;
  10519. this.tempSMask = null;
  10520. this.suspendedCtx = null;
  10521. this.contentVisible = true;
  10522. this.markedContentStack = markedContentStack || [];
  10523. this.optionalContentConfig = optionalContentConfig;
  10524. this.cachedCanvases = new CachedCanvases(this.canvasFactory);
  10525. this.cachedPatterns = new Map();
  10526. this.annotationCanvasMap = annotationCanvasMap;
  10527. this.viewportScale = 1;
  10528. this.outputScaleX = 1;
  10529. this.outputScaleY = 1;
  10530. this.pageColors = pageColors;
  10531. this._cachedScaleForStroking = [-1, 0];
  10532. this._cachedGetSinglePixelWidth = null;
  10533. this._cachedBitmapsMap = new Map();
  10534. }
  10535. getObject(data, fallback = null) {
  10536. if (typeof data === "string") {
  10537. return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
  10538. }
  10539. return fallback;
  10540. }
  10541. beginDrawing({
  10542. transform,
  10543. viewport,
  10544. transparency = false,
  10545. background = null
  10546. }) {
  10547. const width = this.ctx.canvas.width;
  10548. const height = this.ctx.canvas.height;
  10549. const savedFillStyle = this.ctx.fillStyle;
  10550. this.ctx.fillStyle = background || "#ffffff";
  10551. this.ctx.fillRect(0, 0, width, height);
  10552. this.ctx.fillStyle = savedFillStyle;
  10553. if (transparency) {
  10554. const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height);
  10555. this.compositeCtx = this.ctx;
  10556. this.transparentCanvas = transparentCanvas.canvas;
  10557. this.ctx = transparentCanvas.context;
  10558. this.ctx.save();
  10559. this.ctx.transform(...getCurrentTransform(this.compositeCtx));
  10560. }
  10561. this.ctx.save();
  10562. resetCtxToDefault(this.ctx);
  10563. if (transform) {
  10564. this.ctx.transform(...transform);
  10565. this.outputScaleX = transform[0];
  10566. this.outputScaleY = transform[0];
  10567. }
  10568. this.ctx.transform(...viewport.transform);
  10569. this.viewportScale = viewport.scale;
  10570. this.baseTransform = getCurrentTransform(this.ctx);
  10571. }
  10572. executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
  10573. const argsArray = operatorList.argsArray;
  10574. const fnArray = operatorList.fnArray;
  10575. let i = executionStartIdx || 0;
  10576. const argsArrayLen = argsArray.length;
  10577. if (argsArrayLen === i) {
  10578. return i;
  10579. }
  10580. const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
  10581. const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  10582. let steps = 0;
  10583. const commonObjs = this.commonObjs;
  10584. const objs = this.objs;
  10585. let fnId;
  10586. while (true) {
  10587. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  10588. stepper.breakIt(i, continueCallback);
  10589. return i;
  10590. }
  10591. fnId = fnArray[i];
  10592. if (fnId !== OPS.dependency) {
  10593. this[fnId].apply(this, argsArray[i]);
  10594. } else {
  10595. for (const depObjId of argsArray[i]) {
  10596. const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
  10597. if (!objsPool.has(depObjId)) {
  10598. objsPool.get(depObjId, continueCallback);
  10599. return i;
  10600. }
  10601. }
  10602. }
  10603. i++;
  10604. if (i === argsArrayLen) {
  10605. return i;
  10606. }
  10607. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  10608. if (Date.now() > endTime) {
  10609. continueCallback();
  10610. return i;
  10611. }
  10612. steps = 0;
  10613. }
  10614. }
  10615. }
  10616. #restoreInitialState() {
  10617. while (this.stateStack.length || this.inSMaskMode) {
  10618. this.restore();
  10619. }
  10620. this.current.activeSMask = null;
  10621. this.ctx.restore();
  10622. if (this.transparentCanvas) {
  10623. this.ctx = this.compositeCtx;
  10624. this.ctx.save();
  10625. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  10626. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  10627. this.ctx.restore();
  10628. this.transparentCanvas = null;
  10629. }
  10630. }
  10631. endDrawing() {
  10632. this.#restoreInitialState();
  10633. this.cachedCanvases.clear();
  10634. this.cachedPatterns.clear();
  10635. for (const cache of this._cachedBitmapsMap.values()) {
  10636. for (const canvas of cache.values()) {
  10637. if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
  10638. canvas.width = canvas.height = 0;
  10639. }
  10640. }
  10641. cache.clear();
  10642. }
  10643. this._cachedBitmapsMap.clear();
  10644. this.#drawFilter();
  10645. }
  10646. #drawFilter() {
  10647. if (this.pageColors) {
  10648. const hcmFilterId = this.filterFactory.addHCMFilter(this.pageColors.foreground, this.pageColors.background);
  10649. if (hcmFilterId !== "none") {
  10650. const savedFilter = this.ctx.filter;
  10651. this.ctx.filter = hcmFilterId;
  10652. this.ctx.drawImage(this.ctx.canvas, 0, 0);
  10653. this.ctx.filter = savedFilter;
  10654. }
  10655. }
  10656. }
  10657. _scaleImage(img, inverseTransform) {
  10658. const width = img.width;
  10659. const height = img.height;
  10660. let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);
  10661. let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);
  10662. let paintWidth = width,
  10663. paintHeight = height;
  10664. let tmpCanvasId = "prescale1";
  10665. let tmpCanvas, tmpCtx;
  10666. while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
  10667. let newWidth = paintWidth,
  10668. newHeight = paintHeight;
  10669. if (widthScale > 2 && paintWidth > 1) {
  10670. newWidth = paintWidth >= 16384 ? Math.floor(paintWidth / 2) - 1 || 1 : Math.ceil(paintWidth / 2);
  10671. widthScale /= paintWidth / newWidth;
  10672. }
  10673. if (heightScale > 2 && paintHeight > 1) {
  10674. newHeight = paintHeight >= 16384 ? Math.floor(paintHeight / 2) - 1 || 1 : Math.ceil(paintHeight) / 2;
  10675. heightScale /= paintHeight / newHeight;
  10676. }
  10677. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  10678. tmpCtx = tmpCanvas.context;
  10679. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  10680. tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
  10681. img = tmpCanvas.canvas;
  10682. paintWidth = newWidth;
  10683. paintHeight = newHeight;
  10684. tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
  10685. }
  10686. return {
  10687. img,
  10688. paintWidth,
  10689. paintHeight
  10690. };
  10691. }
  10692. _createMaskCanvas(img) {
  10693. const ctx = this.ctx;
  10694. const {
  10695. width,
  10696. height
  10697. } = img;
  10698. const fillColor = this.current.fillColor;
  10699. const isPatternFill = this.current.patternFill;
  10700. const currentTransform = getCurrentTransform(ctx);
  10701. let cache, cacheKey, scaled, maskCanvas;
  10702. if ((img.bitmap || img.data) && img.count > 1) {
  10703. const mainKey = img.bitmap || img.data.buffer;
  10704. cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]);
  10705. cache = this._cachedBitmapsMap.get(mainKey);
  10706. if (!cache) {
  10707. cache = new Map();
  10708. this._cachedBitmapsMap.set(mainKey, cache);
  10709. }
  10710. const cachedImage = cache.get(cacheKey);
  10711. if (cachedImage && !isPatternFill) {
  10712. const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]);
  10713. const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]);
  10714. return {
  10715. canvas: cachedImage,
  10716. offsetX,
  10717. offsetY
  10718. };
  10719. }
  10720. scaled = cachedImage;
  10721. }
  10722. if (!scaled) {
  10723. maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  10724. putBinaryImageMask(maskCanvas.context, img);
  10725. }
  10726. let maskToCanvas = Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]);
  10727. maskToCanvas = Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
  10728. const [minX, minY, maxX, maxY] = Util.getAxialAlignedBoundingBox([0, 0, width, height], maskToCanvas);
  10729. const drawnWidth = Math.round(maxX - minX) || 1;
  10730. const drawnHeight = Math.round(maxY - minY) || 1;
  10731. const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight);
  10732. const fillCtx = fillCanvas.context;
  10733. const offsetX = minX;
  10734. const offsetY = minY;
  10735. fillCtx.translate(-offsetX, -offsetY);
  10736. fillCtx.transform(...maskToCanvas);
  10737. if (!scaled) {
  10738. scaled = this._scaleImage(maskCanvas.canvas, getCurrentTransformInverse(fillCtx));
  10739. scaled = scaled.img;
  10740. if (cache && isPatternFill) {
  10741. cache.set(cacheKey, scaled);
  10742. }
  10743. }
  10744. fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(fillCtx), img.interpolate);
  10745. drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height);
  10746. fillCtx.globalCompositeOperation = "source-in";
  10747. const inverse = Util.transform(getCurrentTransformInverse(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]);
  10748. fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, PathType.FILL) : fillColor;
  10749. fillCtx.fillRect(0, 0, width, height);
  10750. if (cache && !isPatternFill) {
  10751. this.cachedCanvases.delete("fillCanvas");
  10752. cache.set(cacheKey, fillCanvas.canvas);
  10753. }
  10754. return {
  10755. canvas: fillCanvas.canvas,
  10756. offsetX: Math.round(offsetX),
  10757. offsetY: Math.round(offsetY)
  10758. };
  10759. }
  10760. setLineWidth(width) {
  10761. if (width !== this.current.lineWidth) {
  10762. this._cachedScaleForStroking[0] = -1;
  10763. }
  10764. this.current.lineWidth = width;
  10765. this.ctx.lineWidth = width;
  10766. }
  10767. setLineCap(style) {
  10768. this.ctx.lineCap = LINE_CAP_STYLES[style];
  10769. }
  10770. setLineJoin(style) {
  10771. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  10772. }
  10773. setMiterLimit(limit) {
  10774. this.ctx.miterLimit = limit;
  10775. }
  10776. setDash(dashArray, dashPhase) {
  10777. const ctx = this.ctx;
  10778. if (ctx.setLineDash !== undefined) {
  10779. ctx.setLineDash(dashArray);
  10780. ctx.lineDashOffset = dashPhase;
  10781. }
  10782. }
  10783. setRenderingIntent(intent) {}
  10784. setFlatness(flatness) {}
  10785. setGState(states) {
  10786. for (const [key, value] of states) {
  10787. switch (key) {
  10788. case "LW":
  10789. this.setLineWidth(value);
  10790. break;
  10791. case "LC":
  10792. this.setLineCap(value);
  10793. break;
  10794. case "LJ":
  10795. this.setLineJoin(value);
  10796. break;
  10797. case "ML":
  10798. this.setMiterLimit(value);
  10799. break;
  10800. case "D":
  10801. this.setDash(value[0], value[1]);
  10802. break;
  10803. case "RI":
  10804. this.setRenderingIntent(value);
  10805. break;
  10806. case "FL":
  10807. this.setFlatness(value);
  10808. break;
  10809. case "Font":
  10810. this.setFont(value[0], value[1]);
  10811. break;
  10812. case "CA":
  10813. this.current.strokeAlpha = value;
  10814. break;
  10815. case "ca":
  10816. this.current.fillAlpha = value;
  10817. this.ctx.globalAlpha = value;
  10818. break;
  10819. case "BM":
  10820. this.ctx.globalCompositeOperation = value;
  10821. break;
  10822. case "SMask":
  10823. this.current.activeSMask = value ? this.tempSMask : null;
  10824. this.tempSMask = null;
  10825. this.checkSMaskState();
  10826. break;
  10827. case "TR":
  10828. this.ctx.filter = this.current.transferMaps = this.filterFactory.addFilter(value);
  10829. break;
  10830. }
  10831. }
  10832. }
  10833. get inSMaskMode() {
  10834. return !!this.suspendedCtx;
  10835. }
  10836. checkSMaskState() {
  10837. const inSMaskMode = this.inSMaskMode;
  10838. if (this.current.activeSMask && !inSMaskMode) {
  10839. this.beginSMaskMode();
  10840. } else if (!this.current.activeSMask && inSMaskMode) {
  10841. this.endSMaskMode();
  10842. }
  10843. }
  10844. beginSMaskMode() {
  10845. if (this.inSMaskMode) {
  10846. throw new Error("beginSMaskMode called while already in smask mode");
  10847. }
  10848. const drawnWidth = this.ctx.canvas.width;
  10849. const drawnHeight = this.ctx.canvas.height;
  10850. const cacheId = "smaskGroupAt" + this.groupLevel;
  10851. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
  10852. this.suspendedCtx = this.ctx;
  10853. this.ctx = scratchCanvas.context;
  10854. const ctx = this.ctx;
  10855. ctx.setTransform(...getCurrentTransform(this.suspendedCtx));
  10856. copyCtxState(this.suspendedCtx, ctx);
  10857. mirrorContextOperations(ctx, this.suspendedCtx);
  10858. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  10859. }
  10860. endSMaskMode() {
  10861. if (!this.inSMaskMode) {
  10862. throw new Error("endSMaskMode called while not in smask mode");
  10863. }
  10864. this.ctx._removeMirroring();
  10865. copyCtxState(this.ctx, this.suspendedCtx);
  10866. this.ctx = this.suspendedCtx;
  10867. this.suspendedCtx = null;
  10868. }
  10869. compose(dirtyBox) {
  10870. if (!this.current.activeSMask) {
  10871. return;
  10872. }
  10873. if (!dirtyBox) {
  10874. dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];
  10875. } else {
  10876. dirtyBox[0] = Math.floor(dirtyBox[0]);
  10877. dirtyBox[1] = Math.floor(dirtyBox[1]);
  10878. dirtyBox[2] = Math.ceil(dirtyBox[2]);
  10879. dirtyBox[3] = Math.ceil(dirtyBox[3]);
  10880. }
  10881. const smask = this.current.activeSMask;
  10882. const suspendedCtx = this.suspendedCtx;
  10883. this.composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);
  10884. this.ctx.save();
  10885. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  10886. this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
  10887. this.ctx.restore();
  10888. }
  10889. composeSMask(ctx, smask, layerCtx, layerBox) {
  10890. const layerOffsetX = layerBox[0];
  10891. const layerOffsetY = layerBox[1];
  10892. const layerWidth = layerBox[2] - layerOffsetX;
  10893. const layerHeight = layerBox[3] - layerOffsetY;
  10894. if (layerWidth === 0 || layerHeight === 0) {
  10895. return;
  10896. }
  10897. this.genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY);
  10898. ctx.save();
  10899. ctx.globalAlpha = 1;
  10900. ctx.globalCompositeOperation = "source-over";
  10901. ctx.setTransform(1, 0, 0, 1, 0, 0);
  10902. ctx.drawImage(layerCtx.canvas, 0, 0);
  10903. ctx.restore();
  10904. }
  10905. genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) {
  10906. let maskCanvas = maskCtx.canvas;
  10907. let maskX = layerOffsetX - maskOffsetX;
  10908. let maskY = layerOffsetY - maskOffsetY;
  10909. if (backdrop) {
  10910. if (maskX < 0 || maskY < 0 || maskX + width > maskCanvas.width || maskY + height > maskCanvas.height) {
  10911. const canvas = this.cachedCanvases.getCanvas("maskExtension", width, height);
  10912. const ctx = canvas.context;
  10913. ctx.drawImage(maskCanvas, -maskX, -maskY);
  10914. if (backdrop.some(c => c !== 0)) {
  10915. ctx.globalCompositeOperation = "destination-atop";
  10916. ctx.fillStyle = Util.makeHexColor(...backdrop);
  10917. ctx.fillRect(0, 0, width, height);
  10918. ctx.globalCompositeOperation = "source-over";
  10919. }
  10920. maskCanvas = canvas.canvas;
  10921. maskX = maskY = 0;
  10922. } else if (backdrop.some(c => c !== 0)) {
  10923. maskCtx.save();
  10924. maskCtx.globalAlpha = 1;
  10925. maskCtx.setTransform(1, 0, 0, 1, 0, 0);
  10926. const clip = new Path2D();
  10927. clip.rect(maskX, maskY, width, height);
  10928. maskCtx.clip(clip);
  10929. maskCtx.globalCompositeOperation = "destination-atop";
  10930. maskCtx.fillStyle = Util.makeHexColor(...backdrop);
  10931. maskCtx.fillRect(maskX, maskY, width, height);
  10932. maskCtx.restore();
  10933. }
  10934. }
  10935. layerCtx.save();
  10936. layerCtx.globalAlpha = 1;
  10937. layerCtx.setTransform(1, 0, 0, 1, 0, 0);
  10938. if (subtype === "Alpha" && transferMap) {
  10939. layerCtx.filter = this.filterFactory.addAlphaFilter(transferMap);
  10940. } else if (subtype === "Luminosity") {
  10941. layerCtx.filter = this.filterFactory.addLuminosityFilter(transferMap);
  10942. }
  10943. const clip = new Path2D();
  10944. clip.rect(layerOffsetX, layerOffsetY, width, height);
  10945. layerCtx.clip(clip);
  10946. layerCtx.globalCompositeOperation = "destination-in";
  10947. layerCtx.drawImage(maskCanvas, maskX, maskY, width, height, layerOffsetX, layerOffsetY, width, height);
  10948. layerCtx.restore();
  10949. }
  10950. save() {
  10951. if (this.inSMaskMode) {
  10952. copyCtxState(this.ctx, this.suspendedCtx);
  10953. this.suspendedCtx.save();
  10954. } else {
  10955. this.ctx.save();
  10956. }
  10957. const old = this.current;
  10958. this.stateStack.push(old);
  10959. this.current = old.clone();
  10960. }
  10961. restore() {
  10962. if (this.stateStack.length === 0 && this.inSMaskMode) {
  10963. this.endSMaskMode();
  10964. }
  10965. if (this.stateStack.length !== 0) {
  10966. this.current = this.stateStack.pop();
  10967. if (this.inSMaskMode) {
  10968. this.suspendedCtx.restore();
  10969. copyCtxState(this.suspendedCtx, this.ctx);
  10970. } else {
  10971. this.ctx.restore();
  10972. }
  10973. this.checkSMaskState();
  10974. this.pendingClip = null;
  10975. this._cachedScaleForStroking[0] = -1;
  10976. this._cachedGetSinglePixelWidth = null;
  10977. }
  10978. }
  10979. transform(a, b, c, d, e, f) {
  10980. this.ctx.transform(a, b, c, d, e, f);
  10981. this._cachedScaleForStroking[0] = -1;
  10982. this._cachedGetSinglePixelWidth = null;
  10983. }
  10984. constructPath(ops, args, minMax) {
  10985. const ctx = this.ctx;
  10986. const current = this.current;
  10987. let x = current.x,
  10988. y = current.y;
  10989. let startX, startY;
  10990. const currentTransform = getCurrentTransform(ctx);
  10991. const isScalingMatrix = currentTransform[0] === 0 && currentTransform[3] === 0 || currentTransform[1] === 0 && currentTransform[2] === 0;
  10992. const minMaxForBezier = isScalingMatrix ? minMax.slice(0) : null;
  10993. for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
  10994. switch (ops[i] | 0) {
  10995. case OPS.rectangle:
  10996. x = args[j++];
  10997. y = args[j++];
  10998. const width = args[j++];
  10999. const height = args[j++];
  11000. const xw = x + width;
  11001. const yh = y + height;
  11002. ctx.moveTo(x, y);
  11003. if (width === 0 || height === 0) {
  11004. ctx.lineTo(xw, yh);
  11005. } else {
  11006. ctx.lineTo(xw, y);
  11007. ctx.lineTo(xw, yh);
  11008. ctx.lineTo(x, yh);
  11009. }
  11010. if (!isScalingMatrix) {
  11011. current.updateRectMinMax(currentTransform, [x, y, xw, yh]);
  11012. }
  11013. ctx.closePath();
  11014. break;
  11015. case OPS.moveTo:
  11016. x = args[j++];
  11017. y = args[j++];
  11018. ctx.moveTo(x, y);
  11019. if (!isScalingMatrix) {
  11020. current.updatePathMinMax(currentTransform, x, y);
  11021. }
  11022. break;
  11023. case OPS.lineTo:
  11024. x = args[j++];
  11025. y = args[j++];
  11026. ctx.lineTo(x, y);
  11027. if (!isScalingMatrix) {
  11028. current.updatePathMinMax(currentTransform, x, y);
  11029. }
  11030. break;
  11031. case OPS.curveTo:
  11032. startX = x;
  11033. startY = y;
  11034. x = args[j + 4];
  11035. y = args[j + 5];
  11036. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
  11037. current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], args[j + 2], args[j + 3], x, y, minMaxForBezier);
  11038. j += 6;
  11039. break;
  11040. case OPS.curveTo2:
  11041. startX = x;
  11042. startY = y;
  11043. ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
  11044. current.updateCurvePathMinMax(currentTransform, startX, startY, x, y, args[j], args[j + 1], args[j + 2], args[j + 3], minMaxForBezier);
  11045. x = args[j + 2];
  11046. y = args[j + 3];
  11047. j += 4;
  11048. break;
  11049. case OPS.curveTo3:
  11050. startX = x;
  11051. startY = y;
  11052. x = args[j + 2];
  11053. y = args[j + 3];
  11054. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  11055. current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], x, y, x, y, minMaxForBezier);
  11056. j += 4;
  11057. break;
  11058. case OPS.closePath:
  11059. ctx.closePath();
  11060. break;
  11061. }
  11062. }
  11063. if (isScalingMatrix) {
  11064. current.updateScalingPathMinMax(currentTransform, minMaxForBezier);
  11065. }
  11066. current.setCurrentPoint(x, y);
  11067. }
  11068. closePath() {
  11069. this.ctx.closePath();
  11070. }
  11071. stroke(consumePath = true) {
  11072. const ctx = this.ctx;
  11073. const strokeColor = this.current.strokeColor;
  11074. ctx.globalAlpha = this.current.strokeAlpha;
  11075. if (this.contentVisible) {
  11076. if (typeof strokeColor === "object" && strokeColor?.getPattern) {
  11077. ctx.save();
  11078. ctx.strokeStyle = strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE);
  11079. this.rescaleAndStroke(false);
  11080. ctx.restore();
  11081. } else {
  11082. this.rescaleAndStroke(true);
  11083. }
  11084. }
  11085. if (consumePath) {
  11086. this.consumePath(this.current.getClippedPathBoundingBox());
  11087. }
  11088. ctx.globalAlpha = this.current.fillAlpha;
  11089. }
  11090. closeStroke() {
  11091. this.closePath();
  11092. this.stroke();
  11093. }
  11094. fill(consumePath = true) {
  11095. const ctx = this.ctx;
  11096. const fillColor = this.current.fillColor;
  11097. const isPatternFill = this.current.patternFill;
  11098. let needRestore = false;
  11099. if (isPatternFill) {
  11100. ctx.save();
  11101. ctx.fillStyle = fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL);
  11102. needRestore = true;
  11103. }
  11104. const intersect = this.current.getClippedPathBoundingBox();
  11105. if (this.contentVisible && intersect !== null) {
  11106. if (this.pendingEOFill) {
  11107. ctx.fill("evenodd");
  11108. this.pendingEOFill = false;
  11109. } else {
  11110. ctx.fill();
  11111. }
  11112. }
  11113. if (needRestore) {
  11114. ctx.restore();
  11115. }
  11116. if (consumePath) {
  11117. this.consumePath(intersect);
  11118. }
  11119. }
  11120. eoFill() {
  11121. this.pendingEOFill = true;
  11122. this.fill();
  11123. }
  11124. fillStroke() {
  11125. this.fill(false);
  11126. this.stroke(false);
  11127. this.consumePath();
  11128. }
  11129. eoFillStroke() {
  11130. this.pendingEOFill = true;
  11131. this.fillStroke();
  11132. }
  11133. closeFillStroke() {
  11134. this.closePath();
  11135. this.fillStroke();
  11136. }
  11137. closeEOFillStroke() {
  11138. this.pendingEOFill = true;
  11139. this.closePath();
  11140. this.fillStroke();
  11141. }
  11142. endPath() {
  11143. this.consumePath();
  11144. }
  11145. clip() {
  11146. this.pendingClip = NORMAL_CLIP;
  11147. }
  11148. eoClip() {
  11149. this.pendingClip = EO_CLIP;
  11150. }
  11151. beginText() {
  11152. this.current.textMatrix = IDENTITY_MATRIX;
  11153. this.current.textMatrixScale = 1;
  11154. this.current.x = this.current.lineX = 0;
  11155. this.current.y = this.current.lineY = 0;
  11156. }
  11157. endText() {
  11158. const paths = this.pendingTextPaths;
  11159. const ctx = this.ctx;
  11160. if (paths === undefined) {
  11161. ctx.beginPath();
  11162. return;
  11163. }
  11164. ctx.save();
  11165. ctx.beginPath();
  11166. for (const path of paths) {
  11167. ctx.setTransform(...path.transform);
  11168. ctx.translate(path.x, path.y);
  11169. path.addToPath(ctx, path.fontSize);
  11170. }
  11171. ctx.restore();
  11172. ctx.clip();
  11173. ctx.beginPath();
  11174. delete this.pendingTextPaths;
  11175. }
  11176. setCharSpacing(spacing) {
  11177. this.current.charSpacing = spacing;
  11178. }
  11179. setWordSpacing(spacing) {
  11180. this.current.wordSpacing = spacing;
  11181. }
  11182. setHScale(scale) {
  11183. this.current.textHScale = scale / 100;
  11184. }
  11185. setLeading(leading) {
  11186. this.current.leading = -leading;
  11187. }
  11188. setFont(fontRefName, size) {
  11189. const fontObj = this.commonObjs.get(fontRefName);
  11190. const current = this.current;
  11191. if (!fontObj) {
  11192. throw new Error(`Can't find font for ${fontRefName}`);
  11193. }
  11194. current.fontMatrix = fontObj.fontMatrix || FONT_IDENTITY_MATRIX;
  11195. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
  11196. warn("Invalid font matrix for font " + fontRefName);
  11197. }
  11198. if (size < 0) {
  11199. size = -size;
  11200. current.fontDirection = -1;
  11201. } else {
  11202. current.fontDirection = 1;
  11203. }
  11204. this.current.font = fontObj;
  11205. this.current.fontSize = size;
  11206. if (fontObj.isType3Font) {
  11207. return;
  11208. }
  11209. const name = fontObj.loadedName || "sans-serif";
  11210. const typeface = fontObj.systemFontInfo?.css || `"${name}", ${fontObj.fallbackName}`;
  11211. let bold = "normal";
  11212. if (fontObj.black) {
  11213. bold = "900";
  11214. } else if (fontObj.bold) {
  11215. bold = "bold";
  11216. }
  11217. const italic = fontObj.italic ? "italic" : "normal";
  11218. let browserFontSize = size;
  11219. if (size < MIN_FONT_SIZE) {
  11220. browserFontSize = MIN_FONT_SIZE;
  11221. } else if (size > MAX_FONT_SIZE) {
  11222. browserFontSize = MAX_FONT_SIZE;
  11223. }
  11224. this.current.fontSizeScale = size / browserFontSize;
  11225. this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
  11226. }
  11227. setTextRenderingMode(mode) {
  11228. this.current.textRenderingMode = mode;
  11229. }
  11230. setTextRise(rise) {
  11231. this.current.textRise = rise;
  11232. }
  11233. moveText(x, y) {
  11234. this.current.x = this.current.lineX += x;
  11235. this.current.y = this.current.lineY += y;
  11236. }
  11237. setLeadingMoveText(x, y) {
  11238. this.setLeading(-y);
  11239. this.moveText(x, y);
  11240. }
  11241. setTextMatrix(a, b, c, d, e, f) {
  11242. this.current.textMatrix = [a, b, c, d, e, f];
  11243. this.current.textMatrixScale = Math.hypot(a, b);
  11244. this.current.x = this.current.lineX = 0;
  11245. this.current.y = this.current.lineY = 0;
  11246. }
  11247. nextLine() {
  11248. this.moveText(0, this.current.leading);
  11249. }
  11250. paintChar(character, x, y, patternTransform) {
  11251. const ctx = this.ctx;
  11252. const current = this.current;
  11253. const font = current.font;
  11254. const textRenderingMode = current.textRenderingMode;
  11255. const fontSize = current.fontSize / current.fontSizeScale;
  11256. const fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
  11257. const isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG);
  11258. const patternFill = current.patternFill && !font.missingFile;
  11259. let addToPath;
  11260. if (font.disableFontFace || isAddToPathSet || patternFill) {
  11261. addToPath = font.getPathGenerator(this.commonObjs, character);
  11262. }
  11263. if (font.disableFontFace || patternFill) {
  11264. ctx.save();
  11265. ctx.translate(x, y);
  11266. ctx.beginPath();
  11267. addToPath(ctx, fontSize);
  11268. if (patternTransform) {
  11269. ctx.setTransform(...patternTransform);
  11270. }
  11271. if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  11272. ctx.fill();
  11273. }
  11274. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  11275. ctx.stroke();
  11276. }
  11277. ctx.restore();
  11278. } else {
  11279. if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  11280. ctx.fillText(character, x, y);
  11281. }
  11282. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  11283. ctx.strokeText(character, x, y);
  11284. }
  11285. }
  11286. if (isAddToPathSet) {
  11287. const paths = this.pendingTextPaths ||= [];
  11288. paths.push({
  11289. transform: getCurrentTransform(ctx),
  11290. x,
  11291. y,
  11292. fontSize,
  11293. addToPath
  11294. });
  11295. }
  11296. }
  11297. get isFontSubpixelAAEnabled() {
  11298. const {
  11299. context: ctx
  11300. } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
  11301. ctx.scale(1.5, 1);
  11302. ctx.fillText("I", 0, 10);
  11303. const data = ctx.getImageData(0, 0, 10, 10).data;
  11304. let enabled = false;
  11305. for (let i = 3; i < data.length; i += 4) {
  11306. if (data[i] > 0 && data[i] < 255) {
  11307. enabled = true;
  11308. break;
  11309. }
  11310. }
  11311. return shadow(this, "isFontSubpixelAAEnabled", enabled);
  11312. }
  11313. showText(glyphs) {
  11314. const current = this.current;
  11315. const font = current.font;
  11316. if (font.isType3Font) {
  11317. return this.showType3Text(glyphs);
  11318. }
  11319. const fontSize = current.fontSize;
  11320. if (fontSize === 0) {
  11321. return undefined;
  11322. }
  11323. const ctx = this.ctx;
  11324. const fontSizeScale = current.fontSizeScale;
  11325. const charSpacing = current.charSpacing;
  11326. const wordSpacing = current.wordSpacing;
  11327. const fontDirection = current.fontDirection;
  11328. const textHScale = current.textHScale * fontDirection;
  11329. const glyphsLength = glyphs.length;
  11330. const vertical = font.vertical;
  11331. const spacingDir = vertical ? 1 : -1;
  11332. const defaultVMetrics = font.defaultVMetrics;
  11333. const widthAdvanceScale = fontSize * current.fontMatrix[0];
  11334. const simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
  11335. ctx.save();
  11336. ctx.transform(...current.textMatrix);
  11337. ctx.translate(current.x, current.y + current.textRise);
  11338. if (fontDirection > 0) {
  11339. ctx.scale(textHScale, -1);
  11340. } else {
  11341. ctx.scale(textHScale, 1);
  11342. }
  11343. let patternTransform;
  11344. if (current.patternFill) {
  11345. ctx.save();
  11346. const pattern = current.fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL);
  11347. patternTransform = getCurrentTransform(ctx);
  11348. ctx.restore();
  11349. ctx.fillStyle = pattern;
  11350. }
  11351. let lineWidth = current.lineWidth;
  11352. const scale = current.textMatrixScale;
  11353. if (scale === 0 || lineWidth === 0) {
  11354. const fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
  11355. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  11356. lineWidth = this.getSinglePixelWidth();
  11357. }
  11358. } else {
  11359. lineWidth /= scale;
  11360. }
  11361. if (fontSizeScale !== 1.0) {
  11362. ctx.scale(fontSizeScale, fontSizeScale);
  11363. lineWidth /= fontSizeScale;
  11364. }
  11365. ctx.lineWidth = lineWidth;
  11366. if (font.isInvalidPDFjsFont) {
  11367. const chars = [];
  11368. let width = 0;
  11369. for (const glyph of glyphs) {
  11370. chars.push(glyph.unicode);
  11371. width += glyph.width;
  11372. }
  11373. ctx.fillText(chars.join(""), 0, 0);
  11374. current.x += width * widthAdvanceScale * textHScale;
  11375. ctx.restore();
  11376. this.compose();
  11377. return undefined;
  11378. }
  11379. let x = 0,
  11380. i;
  11381. for (i = 0; i < glyphsLength; ++i) {
  11382. const glyph = glyphs[i];
  11383. if (typeof glyph === "number") {
  11384. x += spacingDir * glyph * fontSize / 1000;
  11385. continue;
  11386. }
  11387. let restoreNeeded = false;
  11388. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  11389. const character = glyph.fontChar;
  11390. const accent = glyph.accent;
  11391. let scaledX, scaledY;
  11392. let width = glyph.width;
  11393. if (vertical) {
  11394. const vmetric = glyph.vmetric || defaultVMetrics;
  11395. const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
  11396. const vy = vmetric[2] * widthAdvanceScale;
  11397. width = vmetric ? -vmetric[0] : width;
  11398. scaledX = vx / fontSizeScale;
  11399. scaledY = (x + vy) / fontSizeScale;
  11400. } else {
  11401. scaledX = x / fontSizeScale;
  11402. scaledY = 0;
  11403. }
  11404. if (font.remeasure && width > 0) {
  11405. const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
  11406. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  11407. const characterScaleX = width / measuredWidth;
  11408. restoreNeeded = true;
  11409. ctx.save();
  11410. ctx.scale(characterScaleX, 1);
  11411. scaledX /= characterScaleX;
  11412. } else if (width !== measuredWidth) {
  11413. scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
  11414. }
  11415. }
  11416. if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
  11417. if (simpleFillText && !accent) {
  11418. ctx.fillText(character, scaledX, scaledY);
  11419. } else {
  11420. this.paintChar(character, scaledX, scaledY, patternTransform);
  11421. if (accent) {
  11422. const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
  11423. const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
  11424. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform);
  11425. }
  11426. }
  11427. }
  11428. const charWidth = vertical ? width * widthAdvanceScale - spacing * fontDirection : width * widthAdvanceScale + spacing * fontDirection;
  11429. x += charWidth;
  11430. if (restoreNeeded) {
  11431. ctx.restore();
  11432. }
  11433. }
  11434. if (vertical) {
  11435. current.y -= x;
  11436. } else {
  11437. current.x += x * textHScale;
  11438. }
  11439. ctx.restore();
  11440. this.compose();
  11441. return undefined;
  11442. }
  11443. showType3Text(glyphs) {
  11444. const ctx = this.ctx;
  11445. const current = this.current;
  11446. const font = current.font;
  11447. const fontSize = current.fontSize;
  11448. const fontDirection = current.fontDirection;
  11449. const spacingDir = font.vertical ? 1 : -1;
  11450. const charSpacing = current.charSpacing;
  11451. const wordSpacing = current.wordSpacing;
  11452. const textHScale = current.textHScale * fontDirection;
  11453. const fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  11454. const glyphsLength = glyphs.length;
  11455. const isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE;
  11456. let i, glyph, width, spacingLength;
  11457. if (isTextInvisible || fontSize === 0) {
  11458. return;
  11459. }
  11460. this._cachedScaleForStroking[0] = -1;
  11461. this._cachedGetSinglePixelWidth = null;
  11462. ctx.save();
  11463. ctx.transform(...current.textMatrix);
  11464. ctx.translate(current.x, current.y);
  11465. ctx.scale(textHScale, fontDirection);
  11466. for (i = 0; i < glyphsLength; ++i) {
  11467. glyph = glyphs[i];
  11468. if (typeof glyph === "number") {
  11469. spacingLength = spacingDir * glyph * fontSize / 1000;
  11470. this.ctx.translate(spacingLength, 0);
  11471. current.x += spacingLength * textHScale;
  11472. continue;
  11473. }
  11474. const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  11475. const operatorList = font.charProcOperatorList[glyph.operatorListId];
  11476. if (!operatorList) {
  11477. warn(`Type3 character "${glyph.operatorListId}" is not available.`);
  11478. continue;
  11479. }
  11480. if (this.contentVisible) {
  11481. this.processingType3 = glyph;
  11482. this.save();
  11483. ctx.scale(fontSize, fontSize);
  11484. ctx.transform(...fontMatrix);
  11485. this.executeOperatorList(operatorList);
  11486. this.restore();
  11487. }
  11488. const transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  11489. width = transformed[0] * fontSize + spacing;
  11490. ctx.translate(width, 0);
  11491. current.x += width * textHScale;
  11492. }
  11493. ctx.restore();
  11494. this.processingType3 = null;
  11495. }
  11496. setCharWidth(xWidth, yWidth) {}
  11497. setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
  11498. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  11499. this.ctx.clip();
  11500. this.endPath();
  11501. }
  11502. getColorN_Pattern(IR) {
  11503. let pattern;
  11504. if (IR[0] === "TilingPattern") {
  11505. const color = IR[1];
  11506. const baseTransform = this.baseTransform || getCurrentTransform(this.ctx);
  11507. const canvasGraphicsFactory = {
  11508. createCanvasGraphics: ctx => new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, {
  11509. optionalContentConfig: this.optionalContentConfig,
  11510. markedContentStack: this.markedContentStack
  11511. })
  11512. };
  11513. pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
  11514. } else {
  11515. pattern = this._getPattern(IR[1], IR[2]);
  11516. }
  11517. return pattern;
  11518. }
  11519. setStrokeColorN() {
  11520. this.current.strokeColor = this.getColorN_Pattern(arguments);
  11521. }
  11522. setFillColorN() {
  11523. this.current.fillColor = this.getColorN_Pattern(arguments);
  11524. this.current.patternFill = true;
  11525. }
  11526. setStrokeRGBColor(r, g, b) {
  11527. this.ctx.strokeStyle = this.current.strokeColor = Util.makeHexColor(r, g, b);
  11528. }
  11529. setStrokeTransparent() {
  11530. this.ctx.strokeStyle = this.current.strokeColor = "transparent";
  11531. }
  11532. setFillRGBColor(r, g, b) {
  11533. this.ctx.fillStyle = this.current.fillColor = Util.makeHexColor(r, g, b);
  11534. this.current.patternFill = false;
  11535. }
  11536. setFillTransparent() {
  11537. this.ctx.fillStyle = this.current.fillColor = "transparent";
  11538. this.current.patternFill = false;
  11539. }
  11540. _getPattern(objId, matrix = null) {
  11541. let pattern;
  11542. if (this.cachedPatterns.has(objId)) {
  11543. pattern = this.cachedPatterns.get(objId);
  11544. } else {
  11545. pattern = getShadingPattern(this.getObject(objId));
  11546. this.cachedPatterns.set(objId, pattern);
  11547. }
  11548. if (matrix) {
  11549. pattern.matrix = matrix;
  11550. }
  11551. return pattern;
  11552. }
  11553. shadingFill(objId) {
  11554. if (!this.contentVisible) {
  11555. return;
  11556. }
  11557. const ctx = this.ctx;
  11558. this.save();
  11559. const pattern = this._getPattern(objId);
  11560. ctx.fillStyle = pattern.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.SHADING);
  11561. const inv = getCurrentTransformInverse(ctx);
  11562. if (inv) {
  11563. const {
  11564. width,
  11565. height
  11566. } = ctx.canvas;
  11567. const [x0, y0, x1, y1] = Util.getAxialAlignedBoundingBox([0, 0, width, height], inv);
  11568. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  11569. } else {
  11570. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  11571. }
  11572. this.compose(this.current.getClippedPathBoundingBox());
  11573. this.restore();
  11574. }
  11575. beginInlineImage() {
  11576. unreachable("Should not call beginInlineImage");
  11577. }
  11578. beginImageData() {
  11579. unreachable("Should not call beginImageData");
  11580. }
  11581. paintFormXObjectBegin(matrix, bbox) {
  11582. if (!this.contentVisible) {
  11583. return;
  11584. }
  11585. this.save();
  11586. this.baseTransformStack.push(this.baseTransform);
  11587. if (matrix) {
  11588. this.transform(...matrix);
  11589. }
  11590. this.baseTransform = getCurrentTransform(this.ctx);
  11591. if (bbox) {
  11592. const width = bbox[2] - bbox[0];
  11593. const height = bbox[3] - bbox[1];
  11594. this.ctx.rect(bbox[0], bbox[1], width, height);
  11595. this.current.updateRectMinMax(getCurrentTransform(this.ctx), bbox);
  11596. this.clip();
  11597. this.endPath();
  11598. }
  11599. }
  11600. paintFormXObjectEnd() {
  11601. if (!this.contentVisible) {
  11602. return;
  11603. }
  11604. this.restore();
  11605. this.baseTransform = this.baseTransformStack.pop();
  11606. }
  11607. beginGroup(group) {
  11608. if (!this.contentVisible) {
  11609. return;
  11610. }
  11611. this.save();
  11612. if (this.inSMaskMode) {
  11613. this.endSMaskMode();
  11614. this.current.activeSMask = null;
  11615. }
  11616. const currentCtx = this.ctx;
  11617. if (!group.isolated) {
  11618. info("TODO: Support non-isolated groups.");
  11619. }
  11620. if (group.knockout) {
  11621. warn("Knockout groups not supported.");
  11622. }
  11623. const currentTransform = getCurrentTransform(currentCtx);
  11624. if (group.matrix) {
  11625. currentCtx.transform(...group.matrix);
  11626. }
  11627. if (!group.bbox) {
  11628. throw new Error("Bounding box is required.");
  11629. }
  11630. let bounds = Util.getAxialAlignedBoundingBox(group.bbox, getCurrentTransform(currentCtx));
  11631. const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
  11632. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  11633. const offsetX = Math.floor(bounds[0]);
  11634. const offsetY = Math.floor(bounds[1]);
  11635. const drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  11636. const drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  11637. this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);
  11638. let cacheId = "groupAt" + this.groupLevel;
  11639. if (group.smask) {
  11640. cacheId += "_smask_" + this.smaskCounter++ % 2;
  11641. }
  11642. const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
  11643. const groupCtx = scratchCanvas.context;
  11644. groupCtx.translate(-offsetX, -offsetY);
  11645. groupCtx.transform(...currentTransform);
  11646. if (group.smask) {
  11647. this.smaskStack.push({
  11648. canvas: scratchCanvas.canvas,
  11649. context: groupCtx,
  11650. offsetX,
  11651. offsetY,
  11652. subtype: group.smask.subtype,
  11653. backdrop: group.smask.backdrop,
  11654. transferMap: group.smask.transferMap || null,
  11655. startTransformInverse: null
  11656. });
  11657. } else {
  11658. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  11659. currentCtx.translate(offsetX, offsetY);
  11660. currentCtx.save();
  11661. }
  11662. copyCtxState(currentCtx, groupCtx);
  11663. this.ctx = groupCtx;
  11664. this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  11665. this.groupStack.push(currentCtx);
  11666. this.groupLevel++;
  11667. }
  11668. endGroup(group) {
  11669. if (!this.contentVisible) {
  11670. return;
  11671. }
  11672. this.groupLevel--;
  11673. const groupCtx = this.ctx;
  11674. const ctx = this.groupStack.pop();
  11675. this.ctx = ctx;
  11676. this.ctx.imageSmoothingEnabled = false;
  11677. if (group.smask) {
  11678. this.tempSMask = this.smaskStack.pop();
  11679. this.restore();
  11680. } else {
  11681. this.ctx.restore();
  11682. const currentMtx = getCurrentTransform(this.ctx);
  11683. this.restore();
  11684. this.ctx.save();
  11685. this.ctx.setTransform(...currentMtx);
  11686. const dirtyBox = Util.getAxialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx);
  11687. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  11688. this.ctx.restore();
  11689. this.compose(dirtyBox);
  11690. }
  11691. }
  11692. beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) {
  11693. this.#restoreInitialState();
  11694. resetCtxToDefault(this.ctx);
  11695. this.ctx.save();
  11696. this.save();
  11697. if (this.baseTransform) {
  11698. this.ctx.setTransform(...this.baseTransform);
  11699. }
  11700. if (rect) {
  11701. const width = rect[2] - rect[0];
  11702. const height = rect[3] - rect[1];
  11703. if (hasOwnCanvas && this.annotationCanvasMap) {
  11704. transform = transform.slice();
  11705. transform[4] -= rect[0];
  11706. transform[5] -= rect[1];
  11707. rect = rect.slice();
  11708. rect[0] = rect[1] = 0;
  11709. rect[2] = width;
  11710. rect[3] = height;
  11711. const [scaleX, scaleY] = Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx));
  11712. const {
  11713. viewportScale
  11714. } = this;
  11715. const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale);
  11716. const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale);
  11717. this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight);
  11718. const {
  11719. canvas,
  11720. context
  11721. } = this.annotationCanvas;
  11722. this.annotationCanvasMap.set(id, canvas);
  11723. this.annotationCanvas.savedCtx = this.ctx;
  11724. this.ctx = context;
  11725. this.ctx.save();
  11726. this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY);
  11727. resetCtxToDefault(this.ctx);
  11728. } else {
  11729. resetCtxToDefault(this.ctx);
  11730. this.endPath();
  11731. this.ctx.rect(rect[0], rect[1], width, height);
  11732. this.ctx.clip();
  11733. this.ctx.beginPath();
  11734. }
  11735. }
  11736. this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
  11737. this.transform(...transform);
  11738. this.transform(...matrix);
  11739. }
  11740. endAnnotation() {
  11741. if (this.annotationCanvas) {
  11742. this.ctx.restore();
  11743. this.#drawFilter();
  11744. this.ctx = this.annotationCanvas.savedCtx;
  11745. delete this.annotationCanvas.savedCtx;
  11746. delete this.annotationCanvas;
  11747. }
  11748. }
  11749. paintImageMaskXObject(img) {
  11750. if (!this.contentVisible) {
  11751. return;
  11752. }
  11753. const count = img.count;
  11754. img = this.getObject(img.data, img);
  11755. img.count = count;
  11756. const ctx = this.ctx;
  11757. const glyph = this.processingType3;
  11758. if (glyph) {
  11759. if (glyph.compiled === undefined) {
  11760. glyph.compiled = compileType3Glyph(img);
  11761. }
  11762. if (glyph.compiled) {
  11763. glyph.compiled(ctx);
  11764. return;
  11765. }
  11766. }
  11767. const mask = this._createMaskCanvas(img);
  11768. const maskCanvas = mask.canvas;
  11769. ctx.save();
  11770. ctx.setTransform(1, 0, 0, 1, 0, 0);
  11771. ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
  11772. ctx.restore();
  11773. this.compose();
  11774. }
  11775. paintImageMaskXObjectRepeat(img, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
  11776. if (!this.contentVisible) {
  11777. return;
  11778. }
  11779. img = this.getObject(img.data, img);
  11780. const ctx = this.ctx;
  11781. ctx.save();
  11782. const currentTransform = getCurrentTransform(ctx);
  11783. ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
  11784. const mask = this._createMaskCanvas(img);
  11785. ctx.setTransform(1, 0, 0, 1, mask.offsetX - currentTransform[4], mask.offsetY - currentTransform[5]);
  11786. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  11787. const trans = Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]);
  11788. const [x, y] = Util.applyTransform([0, 0], trans);
  11789. ctx.drawImage(mask.canvas, x, y);
  11790. }
  11791. ctx.restore();
  11792. this.compose();
  11793. }
  11794. paintImageMaskXObjectGroup(images) {
  11795. if (!this.contentVisible) {
  11796. return;
  11797. }
  11798. const ctx = this.ctx;
  11799. const fillColor = this.current.fillColor;
  11800. const isPatternFill = this.current.patternFill;
  11801. for (const image of images) {
  11802. const {
  11803. data,
  11804. width,
  11805. height,
  11806. transform
  11807. } = image;
  11808. const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
  11809. const maskCtx = maskCanvas.context;
  11810. maskCtx.save();
  11811. const img = this.getObject(data, image);
  11812. putBinaryImageMask(maskCtx, img);
  11813. maskCtx.globalCompositeOperation = "source-in";
  11814. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, getCurrentTransformInverse(ctx), PathType.FILL) : fillColor;
  11815. maskCtx.fillRect(0, 0, width, height);
  11816. maskCtx.restore();
  11817. ctx.save();
  11818. ctx.transform(...transform);
  11819. ctx.scale(1, -1);
  11820. drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  11821. ctx.restore();
  11822. }
  11823. this.compose();
  11824. }
  11825. paintImageXObject(objId) {
  11826. if (!this.contentVisible) {
  11827. return;
  11828. }
  11829. const imgData = this.getObject(objId);
  11830. if (!imgData) {
  11831. warn("Dependent image isn't ready yet");
  11832. return;
  11833. }
  11834. this.paintInlineImageXObject(imgData);
  11835. }
  11836. paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
  11837. if (!this.contentVisible) {
  11838. return;
  11839. }
  11840. const imgData = this.getObject(objId);
  11841. if (!imgData) {
  11842. warn("Dependent image isn't ready yet");
  11843. return;
  11844. }
  11845. const width = imgData.width;
  11846. const height = imgData.height;
  11847. const map = [];
  11848. for (let i = 0, ii = positions.length; i < ii; i += 2) {
  11849. map.push({
  11850. transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
  11851. x: 0,
  11852. y: 0,
  11853. w: width,
  11854. h: height
  11855. });
  11856. }
  11857. this.paintInlineImageXObjectGroup(imgData, map);
  11858. }
  11859. applyTransferMapsToCanvas(ctx) {
  11860. if (this.current.transferMaps !== "none") {
  11861. ctx.filter = this.current.transferMaps;
  11862. ctx.drawImage(ctx.canvas, 0, 0);
  11863. ctx.filter = "none";
  11864. }
  11865. return ctx.canvas;
  11866. }
  11867. applyTransferMapsToBitmap(imgData) {
  11868. if (this.current.transferMaps === "none") {
  11869. return imgData.bitmap;
  11870. }
  11871. const {
  11872. bitmap,
  11873. width,
  11874. height
  11875. } = imgData;
  11876. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
  11877. const tmpCtx = tmpCanvas.context;
  11878. tmpCtx.filter = this.current.transferMaps;
  11879. tmpCtx.drawImage(bitmap, 0, 0);
  11880. tmpCtx.filter = "none";
  11881. return tmpCanvas.canvas;
  11882. }
  11883. paintInlineImageXObject(imgData) {
  11884. if (!this.contentVisible) {
  11885. return;
  11886. }
  11887. const width = imgData.width;
  11888. const height = imgData.height;
  11889. const ctx = this.ctx;
  11890. this.save();
  11891. if (!isNodeJS) {
  11892. const {
  11893. filter
  11894. } = ctx;
  11895. if (filter !== "none" && filter !== "") {
  11896. ctx.filter = "none";
  11897. }
  11898. }
  11899. ctx.scale(1 / width, -1 / height);
  11900. let imgToPaint;
  11901. if (imgData.bitmap) {
  11902. imgToPaint = this.applyTransferMapsToBitmap(imgData);
  11903. } else if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
  11904. imgToPaint = imgData;
  11905. } else {
  11906. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
  11907. const tmpCtx = tmpCanvas.context;
  11908. putBinaryImageData(tmpCtx, imgData);
  11909. imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);
  11910. }
  11911. const scaled = this._scaleImage(imgToPaint, getCurrentTransformInverse(ctx));
  11912. ctx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(ctx), imgData.interpolate);
  11913. drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
  11914. this.compose();
  11915. this.restore();
  11916. }
  11917. paintInlineImageXObjectGroup(imgData, map) {
  11918. if (!this.contentVisible) {
  11919. return;
  11920. }
  11921. const ctx = this.ctx;
  11922. let imgToPaint;
  11923. if (imgData.bitmap) {
  11924. imgToPaint = imgData.bitmap;
  11925. } else {
  11926. const w = imgData.width;
  11927. const h = imgData.height;
  11928. const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);
  11929. const tmpCtx = tmpCanvas.context;
  11930. putBinaryImageData(tmpCtx, imgData);
  11931. imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);
  11932. }
  11933. for (const entry of map) {
  11934. ctx.save();
  11935. ctx.transform(...entry.transform);
  11936. ctx.scale(1, -1);
  11937. drawImageAtIntegerCoords(ctx, imgToPaint, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
  11938. ctx.restore();
  11939. }
  11940. this.compose();
  11941. }
  11942. paintSolidColorImageMask() {
  11943. if (!this.contentVisible) {
  11944. return;
  11945. }
  11946. this.ctx.fillRect(0, 0, 1, 1);
  11947. this.compose();
  11948. }
  11949. markPoint(tag) {}
  11950. markPointProps(tag, properties) {}
  11951. beginMarkedContent(tag) {
  11952. this.markedContentStack.push({
  11953. visible: true
  11954. });
  11955. }
  11956. beginMarkedContentProps(tag, properties) {
  11957. if (tag === "OC") {
  11958. this.markedContentStack.push({
  11959. visible: this.optionalContentConfig.isVisible(properties)
  11960. });
  11961. } else {
  11962. this.markedContentStack.push({
  11963. visible: true
  11964. });
  11965. }
  11966. this.contentVisible = this.isContentVisible();
  11967. }
  11968. endMarkedContent() {
  11969. this.markedContentStack.pop();
  11970. this.contentVisible = this.isContentVisible();
  11971. }
  11972. beginCompat() {}
  11973. endCompat() {}
  11974. consumePath(clipBox) {
  11975. const isEmpty = this.current.isEmptyClip();
  11976. if (this.pendingClip) {
  11977. this.current.updateClipFromPath();
  11978. }
  11979. if (!this.pendingClip) {
  11980. this.compose(clipBox);
  11981. }
  11982. const ctx = this.ctx;
  11983. if (this.pendingClip) {
  11984. if (!isEmpty) {
  11985. if (this.pendingClip === EO_CLIP) {
  11986. ctx.clip("evenodd");
  11987. } else {
  11988. ctx.clip();
  11989. }
  11990. }
  11991. this.pendingClip = null;
  11992. }
  11993. this.current.startNewPathAndClipBox(this.current.clipBox);
  11994. ctx.beginPath();
  11995. }
  11996. getSinglePixelWidth() {
  11997. if (!this._cachedGetSinglePixelWidth) {
  11998. const m = getCurrentTransform(this.ctx);
  11999. if (m[1] === 0 && m[2] === 0) {
  12000. this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3]));
  12001. } else {
  12002. const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
  12003. const normX = Math.hypot(m[0], m[2]);
  12004. const normY = Math.hypot(m[1], m[3]);
  12005. this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;
  12006. }
  12007. }
  12008. return this._cachedGetSinglePixelWidth;
  12009. }
  12010. getScaleForStroking() {
  12011. if (this._cachedScaleForStroking[0] === -1) {
  12012. const {
  12013. lineWidth
  12014. } = this.current;
  12015. const {
  12016. a,
  12017. b,
  12018. c,
  12019. d
  12020. } = this.ctx.getTransform();
  12021. let scaleX, scaleY;
  12022. if (b === 0 && c === 0) {
  12023. const normX = Math.abs(a);
  12024. const normY = Math.abs(d);
  12025. if (normX === normY) {
  12026. if (lineWidth === 0) {
  12027. scaleX = scaleY = 1 / normX;
  12028. } else {
  12029. const scaledLineWidth = normX * lineWidth;
  12030. scaleX = scaleY = scaledLineWidth < 1 ? 1 / scaledLineWidth : 1;
  12031. }
  12032. } else if (lineWidth === 0) {
  12033. scaleX = 1 / normX;
  12034. scaleY = 1 / normY;
  12035. } else {
  12036. const scaledXLineWidth = normX * lineWidth;
  12037. const scaledYLineWidth = normY * lineWidth;
  12038. scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;
  12039. scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;
  12040. }
  12041. } else {
  12042. const absDet = Math.abs(a * d - b * c);
  12043. const normX = Math.hypot(a, b);
  12044. const normY = Math.hypot(c, d);
  12045. if (lineWidth === 0) {
  12046. scaleX = normY / absDet;
  12047. scaleY = normX / absDet;
  12048. } else {
  12049. const baseArea = lineWidth * absDet;
  12050. scaleX = normY > baseArea ? normY / baseArea : 1;
  12051. scaleY = normX > baseArea ? normX / baseArea : 1;
  12052. }
  12053. }
  12054. this._cachedScaleForStroking[0] = scaleX;
  12055. this._cachedScaleForStroking[1] = scaleY;
  12056. }
  12057. return this._cachedScaleForStroking;
  12058. }
  12059. rescaleAndStroke(saveRestore) {
  12060. const {
  12061. ctx
  12062. } = this;
  12063. const {
  12064. lineWidth
  12065. } = this.current;
  12066. const [scaleX, scaleY] = this.getScaleForStroking();
  12067. ctx.lineWidth = lineWidth || 1;
  12068. if (scaleX === 1 && scaleY === 1) {
  12069. ctx.stroke();
  12070. return;
  12071. }
  12072. const dashes = ctx.getLineDash();
  12073. if (saveRestore) {
  12074. ctx.save();
  12075. }
  12076. ctx.scale(scaleX, scaleY);
  12077. if (dashes.length > 0) {
  12078. const scale = Math.max(scaleX, scaleY);
  12079. ctx.setLineDash(dashes.map(x => x / scale));
  12080. ctx.lineDashOffset /= scale;
  12081. }
  12082. ctx.stroke();
  12083. if (saveRestore) {
  12084. ctx.restore();
  12085. }
  12086. }
  12087. isContentVisible() {
  12088. for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
  12089. if (!this.markedContentStack[i].visible) {
  12090. return false;
  12091. }
  12092. }
  12093. return true;
  12094. }
  12095. }
  12096. for (const op in OPS) {
  12097. if (CanvasGraphics.prototype[op] !== undefined) {
  12098. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  12099. }
  12100. }
  12101. ;// ./src/display/worker_options.js
  12102. class GlobalWorkerOptions {
  12103. static #port = null;
  12104. static #src = "";
  12105. static get workerPort() {
  12106. return this.#port;
  12107. }
  12108. static set workerPort(val) {
  12109. if (!(typeof Worker !== "undefined" && val instanceof Worker) && val !== null) {
  12110. throw new Error("Invalid `workerPort` type.");
  12111. }
  12112. this.#port = val;
  12113. }
  12114. static get workerSrc() {
  12115. return this.#src;
  12116. }
  12117. static set workerSrc(val) {
  12118. if (typeof val !== "string") {
  12119. throw new Error("Invalid `workerSrc` type.");
  12120. }
  12121. this.#src = val;
  12122. }
  12123. }
  12124. ;// ./src/shared/message_handler.js
  12125. const CallbackKind = {
  12126. UNKNOWN: 0,
  12127. DATA: 1,
  12128. ERROR: 2
  12129. };
  12130. const StreamKind = {
  12131. UNKNOWN: 0,
  12132. CANCEL: 1,
  12133. CANCEL_COMPLETE: 2,
  12134. CLOSE: 3,
  12135. ENQUEUE: 4,
  12136. ERROR: 5,
  12137. PULL: 6,
  12138. PULL_COMPLETE: 7,
  12139. START_COMPLETE: 8
  12140. };
  12141. function wrapReason(reason) {
  12142. if (!(reason instanceof Error || typeof reason === "object" && reason !== null)) {
  12143. unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
  12144. }
  12145. switch (reason.name) {
  12146. case "AbortException":
  12147. return new AbortException(reason.message);
  12148. case "MissingPDFException":
  12149. return new MissingPDFException(reason.message);
  12150. case "PasswordException":
  12151. return new PasswordException(reason.message, reason.code);
  12152. case "UnexpectedResponseException":
  12153. return new UnexpectedResponseException(reason.message, reason.status);
  12154. case "UnknownErrorException":
  12155. return new UnknownErrorException(reason.message, reason.details);
  12156. default:
  12157. return new UnknownErrorException(reason.message, reason.toString());
  12158. }
  12159. }
  12160. class MessageHandler {
  12161. constructor(sourceName, targetName, comObj) {
  12162. this.sourceName = sourceName;
  12163. this.targetName = targetName;
  12164. this.comObj = comObj;
  12165. this.callbackId = 1;
  12166. this.streamId = 1;
  12167. this.streamSinks = Object.create(null);
  12168. this.streamControllers = Object.create(null);
  12169. this.callbackCapabilities = Object.create(null);
  12170. this.actionHandler = Object.create(null);
  12171. this._onComObjOnMessage = event => {
  12172. const data = event.data;
  12173. if (data.targetName !== this.sourceName) {
  12174. return;
  12175. }
  12176. if (data.stream) {
  12177. this.#processStreamMessage(data);
  12178. return;
  12179. }
  12180. if (data.callback) {
  12181. const callbackId = data.callbackId;
  12182. const capability = this.callbackCapabilities[callbackId];
  12183. if (!capability) {
  12184. throw new Error(`Cannot resolve callback ${callbackId}`);
  12185. }
  12186. delete this.callbackCapabilities[callbackId];
  12187. if (data.callback === CallbackKind.DATA) {
  12188. capability.resolve(data.data);
  12189. } else if (data.callback === CallbackKind.ERROR) {
  12190. capability.reject(wrapReason(data.reason));
  12191. } else {
  12192. throw new Error("Unexpected callback case");
  12193. }
  12194. return;
  12195. }
  12196. const action = this.actionHandler[data.action];
  12197. if (!action) {
  12198. throw new Error(`Unknown action from worker: ${data.action}`);
  12199. }
  12200. if (data.callbackId) {
  12201. const cbSourceName = this.sourceName;
  12202. const cbTargetName = data.sourceName;
  12203. new Promise(function (resolve) {
  12204. resolve(action(data.data));
  12205. }).then(function (result) {
  12206. comObj.postMessage({
  12207. sourceName: cbSourceName,
  12208. targetName: cbTargetName,
  12209. callback: CallbackKind.DATA,
  12210. callbackId: data.callbackId,
  12211. data: result
  12212. });
  12213. }, function (reason) {
  12214. comObj.postMessage({
  12215. sourceName: cbSourceName,
  12216. targetName: cbTargetName,
  12217. callback: CallbackKind.ERROR,
  12218. callbackId: data.callbackId,
  12219. reason: wrapReason(reason)
  12220. });
  12221. });
  12222. return;
  12223. }
  12224. if (data.streamId) {
  12225. this.#createStreamSink(data);
  12226. return;
  12227. }
  12228. action(data.data);
  12229. };
  12230. comObj.addEventListener("message", this._onComObjOnMessage);
  12231. }
  12232. on(actionName, handler) {
  12233. const ah = this.actionHandler;
  12234. if (ah[actionName]) {
  12235. throw new Error(`There is already an actionName called "${actionName}"`);
  12236. }
  12237. ah[actionName] = handler;
  12238. }
  12239. send(actionName, data, transfers) {
  12240. this.comObj.postMessage({
  12241. sourceName: this.sourceName,
  12242. targetName: this.targetName,
  12243. action: actionName,
  12244. data
  12245. }, transfers);
  12246. }
  12247. sendWithPromise(actionName, data, transfers) {
  12248. const callbackId = this.callbackId++;
  12249. const capability = Promise.withResolvers();
  12250. this.callbackCapabilities[callbackId] = capability;
  12251. try {
  12252. this.comObj.postMessage({
  12253. sourceName: this.sourceName,
  12254. targetName: this.targetName,
  12255. action: actionName,
  12256. callbackId,
  12257. data
  12258. }, transfers);
  12259. } catch (ex) {
  12260. capability.reject(ex);
  12261. }
  12262. return capability.promise;
  12263. }
  12264. sendWithStream(actionName, data, queueingStrategy, transfers) {
  12265. const streamId = this.streamId++,
  12266. sourceName = this.sourceName,
  12267. targetName = this.targetName,
  12268. comObj = this.comObj;
  12269. return new ReadableStream({
  12270. start: controller => {
  12271. const startCapability = Promise.withResolvers();
  12272. this.streamControllers[streamId] = {
  12273. controller,
  12274. startCall: startCapability,
  12275. pullCall: null,
  12276. cancelCall: null,
  12277. isClosed: false
  12278. };
  12279. comObj.postMessage({
  12280. sourceName,
  12281. targetName,
  12282. action: actionName,
  12283. streamId,
  12284. data,
  12285. desiredSize: controller.desiredSize
  12286. }, transfers);
  12287. return startCapability.promise;
  12288. },
  12289. pull: controller => {
  12290. const pullCapability = Promise.withResolvers();
  12291. this.streamControllers[streamId].pullCall = pullCapability;
  12292. comObj.postMessage({
  12293. sourceName,
  12294. targetName,
  12295. stream: StreamKind.PULL,
  12296. streamId,
  12297. desiredSize: controller.desiredSize
  12298. });
  12299. return pullCapability.promise;
  12300. },
  12301. cancel: reason => {
  12302. assert(reason instanceof Error, "cancel must have a valid reason");
  12303. const cancelCapability = Promise.withResolvers();
  12304. this.streamControllers[streamId].cancelCall = cancelCapability;
  12305. this.streamControllers[streamId].isClosed = true;
  12306. comObj.postMessage({
  12307. sourceName,
  12308. targetName,
  12309. stream: StreamKind.CANCEL,
  12310. streamId,
  12311. reason: wrapReason(reason)
  12312. });
  12313. return cancelCapability.promise;
  12314. }
  12315. }, queueingStrategy);
  12316. }
  12317. #createStreamSink(data) {
  12318. const streamId = data.streamId,
  12319. sourceName = this.sourceName,
  12320. targetName = data.sourceName,
  12321. comObj = this.comObj;
  12322. const self = this,
  12323. action = this.actionHandler[data.action];
  12324. const streamSink = {
  12325. enqueue(chunk, size = 1, transfers) {
  12326. if (this.isCancelled) {
  12327. return;
  12328. }
  12329. const lastDesiredSize = this.desiredSize;
  12330. this.desiredSize -= size;
  12331. if (lastDesiredSize > 0 && this.desiredSize <= 0) {
  12332. this.sinkCapability = Promise.withResolvers();
  12333. this.ready = this.sinkCapability.promise;
  12334. }
  12335. comObj.postMessage({
  12336. sourceName,
  12337. targetName,
  12338. stream: StreamKind.ENQUEUE,
  12339. streamId,
  12340. chunk
  12341. }, transfers);
  12342. },
  12343. close() {
  12344. if (this.isCancelled) {
  12345. return;
  12346. }
  12347. this.isCancelled = true;
  12348. comObj.postMessage({
  12349. sourceName,
  12350. targetName,
  12351. stream: StreamKind.CLOSE,
  12352. streamId
  12353. });
  12354. delete self.streamSinks[streamId];
  12355. },
  12356. error(reason) {
  12357. assert(reason instanceof Error, "error must have a valid reason");
  12358. if (this.isCancelled) {
  12359. return;
  12360. }
  12361. this.isCancelled = true;
  12362. comObj.postMessage({
  12363. sourceName,
  12364. targetName,
  12365. stream: StreamKind.ERROR,
  12366. streamId,
  12367. reason: wrapReason(reason)
  12368. });
  12369. },
  12370. sinkCapability: Promise.withResolvers(),
  12371. onPull: null,
  12372. onCancel: null,
  12373. isCancelled: false,
  12374. desiredSize: data.desiredSize,
  12375. ready: null
  12376. };
  12377. streamSink.sinkCapability.resolve();
  12378. streamSink.ready = streamSink.sinkCapability.promise;
  12379. this.streamSinks[streamId] = streamSink;
  12380. new Promise(function (resolve) {
  12381. resolve(action(data.data, streamSink));
  12382. }).then(function () {
  12383. comObj.postMessage({
  12384. sourceName,
  12385. targetName,
  12386. stream: StreamKind.START_COMPLETE,
  12387. streamId,
  12388. success: true
  12389. });
  12390. }, function (reason) {
  12391. comObj.postMessage({
  12392. sourceName,
  12393. targetName,
  12394. stream: StreamKind.START_COMPLETE,
  12395. streamId,
  12396. reason: wrapReason(reason)
  12397. });
  12398. });
  12399. }
  12400. #processStreamMessage(data) {
  12401. const streamId = data.streamId,
  12402. sourceName = this.sourceName,
  12403. targetName = data.sourceName,
  12404. comObj = this.comObj;
  12405. const streamController = this.streamControllers[streamId],
  12406. streamSink = this.streamSinks[streamId];
  12407. switch (data.stream) {
  12408. case StreamKind.START_COMPLETE:
  12409. if (data.success) {
  12410. streamController.startCall.resolve();
  12411. } else {
  12412. streamController.startCall.reject(wrapReason(data.reason));
  12413. }
  12414. break;
  12415. case StreamKind.PULL_COMPLETE:
  12416. if (data.success) {
  12417. streamController.pullCall.resolve();
  12418. } else {
  12419. streamController.pullCall.reject(wrapReason(data.reason));
  12420. }
  12421. break;
  12422. case StreamKind.PULL:
  12423. if (!streamSink) {
  12424. comObj.postMessage({
  12425. sourceName,
  12426. targetName,
  12427. stream: StreamKind.PULL_COMPLETE,
  12428. streamId,
  12429. success: true
  12430. });
  12431. break;
  12432. }
  12433. if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {
  12434. streamSink.sinkCapability.resolve();
  12435. }
  12436. streamSink.desiredSize = data.desiredSize;
  12437. new Promise(function (resolve) {
  12438. resolve(streamSink.onPull?.());
  12439. }).then(function () {
  12440. comObj.postMessage({
  12441. sourceName,
  12442. targetName,
  12443. stream: StreamKind.PULL_COMPLETE,
  12444. streamId,
  12445. success: true
  12446. });
  12447. }, function (reason) {
  12448. comObj.postMessage({
  12449. sourceName,
  12450. targetName,
  12451. stream: StreamKind.PULL_COMPLETE,
  12452. streamId,
  12453. reason: wrapReason(reason)
  12454. });
  12455. });
  12456. break;
  12457. case StreamKind.ENQUEUE:
  12458. assert(streamController, "enqueue should have stream controller");
  12459. if (streamController.isClosed) {
  12460. break;
  12461. }
  12462. streamController.controller.enqueue(data.chunk);
  12463. break;
  12464. case StreamKind.CLOSE:
  12465. assert(streamController, "close should have stream controller");
  12466. if (streamController.isClosed) {
  12467. break;
  12468. }
  12469. streamController.isClosed = true;
  12470. streamController.controller.close();
  12471. this.#deleteStreamController(streamController, streamId);
  12472. break;
  12473. case StreamKind.ERROR:
  12474. assert(streamController, "error should have stream controller");
  12475. streamController.controller.error(wrapReason(data.reason));
  12476. this.#deleteStreamController(streamController, streamId);
  12477. break;
  12478. case StreamKind.CANCEL_COMPLETE:
  12479. if (data.success) {
  12480. streamController.cancelCall.resolve();
  12481. } else {
  12482. streamController.cancelCall.reject(wrapReason(data.reason));
  12483. }
  12484. this.#deleteStreamController(streamController, streamId);
  12485. break;
  12486. case StreamKind.CANCEL:
  12487. if (!streamSink) {
  12488. break;
  12489. }
  12490. new Promise(function (resolve) {
  12491. resolve(streamSink.onCancel?.(wrapReason(data.reason)));
  12492. }).then(function () {
  12493. comObj.postMessage({
  12494. sourceName,
  12495. targetName,
  12496. stream: StreamKind.CANCEL_COMPLETE,
  12497. streamId,
  12498. success: true
  12499. });
  12500. }, function (reason) {
  12501. comObj.postMessage({
  12502. sourceName,
  12503. targetName,
  12504. stream: StreamKind.CANCEL_COMPLETE,
  12505. streamId,
  12506. reason: wrapReason(reason)
  12507. });
  12508. });
  12509. streamSink.sinkCapability.reject(wrapReason(data.reason));
  12510. streamSink.isCancelled = true;
  12511. delete this.streamSinks[streamId];
  12512. break;
  12513. default:
  12514. throw new Error("Unexpected stream case");
  12515. }
  12516. }
  12517. async #deleteStreamController(streamController, streamId) {
  12518. await Promise.allSettled([streamController.startCall?.promise, streamController.pullCall?.promise, streamController.cancelCall?.promise]);
  12519. delete this.streamControllers[streamId];
  12520. }
  12521. destroy() {
  12522. this.comObj.removeEventListener("message", this._onComObjOnMessage);
  12523. }
  12524. }
  12525. ;// ./src/display/metadata.js
  12526. class Metadata {
  12527. #metadataMap;
  12528. #data;
  12529. constructor({
  12530. parsedData,
  12531. rawData
  12532. }) {
  12533. this.#metadataMap = parsedData;
  12534. this.#data = rawData;
  12535. }
  12536. getRaw() {
  12537. return this.#data;
  12538. }
  12539. get(name) {
  12540. return this.#metadataMap.get(name) ?? null;
  12541. }
  12542. getAll() {
  12543. return objectFromMap(this.#metadataMap);
  12544. }
  12545. has(name) {
  12546. return this.#metadataMap.has(name);
  12547. }
  12548. }
  12549. ;// ./src/display/optional_content_config.js
  12550. const INTERNAL = Symbol("INTERNAL");
  12551. class OptionalContentGroup {
  12552. #isDisplay = false;
  12553. #isPrint = false;
  12554. #userSet = false;
  12555. #visible = true;
  12556. constructor(renderingIntent, {
  12557. name,
  12558. intent,
  12559. usage
  12560. }) {
  12561. this.#isDisplay = !!(renderingIntent & RenderingIntentFlag.DISPLAY);
  12562. this.#isPrint = !!(renderingIntent & RenderingIntentFlag.PRINT);
  12563. this.name = name;
  12564. this.intent = intent;
  12565. this.usage = usage;
  12566. }
  12567. get visible() {
  12568. if (this.#userSet) {
  12569. return this.#visible;
  12570. }
  12571. if (!this.#visible) {
  12572. return false;
  12573. }
  12574. const {
  12575. print,
  12576. view
  12577. } = this.usage;
  12578. if (this.#isDisplay) {
  12579. return view?.viewState !== "OFF";
  12580. } else if (this.#isPrint) {
  12581. return print?.printState !== "OFF";
  12582. }
  12583. return true;
  12584. }
  12585. _setVisible(internal, visible, userSet = false) {
  12586. if (internal !== INTERNAL) {
  12587. unreachable("Internal method `_setVisible` called.");
  12588. }
  12589. this.#userSet = userSet;
  12590. this.#visible = visible;
  12591. }
  12592. }
  12593. class OptionalContentConfig {
  12594. #cachedGetHash = null;
  12595. #groups = new Map();
  12596. #initialHash = null;
  12597. #order = null;
  12598. constructor(data, renderingIntent = RenderingIntentFlag.DISPLAY) {
  12599. this.renderingIntent = renderingIntent;
  12600. this.name = null;
  12601. this.creator = null;
  12602. if (data === null) {
  12603. return;
  12604. }
  12605. this.name = data.name;
  12606. this.creator = data.creator;
  12607. this.#order = data.order;
  12608. for (const group of data.groups) {
  12609. this.#groups.set(group.id, new OptionalContentGroup(renderingIntent, group));
  12610. }
  12611. if (data.baseState === "OFF") {
  12612. for (const group of this.#groups.values()) {
  12613. group._setVisible(INTERNAL, false);
  12614. }
  12615. }
  12616. for (const on of data.on) {
  12617. this.#groups.get(on)._setVisible(INTERNAL, true);
  12618. }
  12619. for (const off of data.off) {
  12620. this.#groups.get(off)._setVisible(INTERNAL, false);
  12621. }
  12622. this.#initialHash = this.getHash();
  12623. }
  12624. #evaluateVisibilityExpression(array) {
  12625. const length = array.length;
  12626. if (length < 2) {
  12627. return true;
  12628. }
  12629. const operator = array[0];
  12630. for (let i = 1; i < length; i++) {
  12631. const element = array[i];
  12632. let state;
  12633. if (Array.isArray(element)) {
  12634. state = this.#evaluateVisibilityExpression(element);
  12635. } else if (this.#groups.has(element)) {
  12636. state = this.#groups.get(element).visible;
  12637. } else {
  12638. warn(`Optional content group not found: ${element}`);
  12639. return true;
  12640. }
  12641. switch (operator) {
  12642. case "And":
  12643. if (!state) {
  12644. return false;
  12645. }
  12646. break;
  12647. case "Or":
  12648. if (state) {
  12649. return true;
  12650. }
  12651. break;
  12652. case "Not":
  12653. return !state;
  12654. default:
  12655. return true;
  12656. }
  12657. }
  12658. return operator === "And";
  12659. }
  12660. isVisible(group) {
  12661. if (this.#groups.size === 0) {
  12662. return true;
  12663. }
  12664. if (!group) {
  12665. info("Optional content group not defined.");
  12666. return true;
  12667. }
  12668. if (group.type === "OCG") {
  12669. if (!this.#groups.has(group.id)) {
  12670. warn(`Optional content group not found: ${group.id}`);
  12671. return true;
  12672. }
  12673. return this.#groups.get(group.id).visible;
  12674. } else if (group.type === "OCMD") {
  12675. if (group.expression) {
  12676. return this.#evaluateVisibilityExpression(group.expression);
  12677. }
  12678. if (!group.policy || group.policy === "AnyOn") {
  12679. for (const id of group.ids) {
  12680. if (!this.#groups.has(id)) {
  12681. warn(`Optional content group not found: ${id}`);
  12682. return true;
  12683. }
  12684. if (this.#groups.get(id).visible) {
  12685. return true;
  12686. }
  12687. }
  12688. return false;
  12689. } else if (group.policy === "AllOn") {
  12690. for (const id of group.ids) {
  12691. if (!this.#groups.has(id)) {
  12692. warn(`Optional content group not found: ${id}`);
  12693. return true;
  12694. }
  12695. if (!this.#groups.get(id).visible) {
  12696. return false;
  12697. }
  12698. }
  12699. return true;
  12700. } else if (group.policy === "AnyOff") {
  12701. for (const id of group.ids) {
  12702. if (!this.#groups.has(id)) {
  12703. warn(`Optional content group not found: ${id}`);
  12704. return true;
  12705. }
  12706. if (!this.#groups.get(id).visible) {
  12707. return true;
  12708. }
  12709. }
  12710. return false;
  12711. } else if (group.policy === "AllOff") {
  12712. for (const id of group.ids) {
  12713. if (!this.#groups.has(id)) {
  12714. warn(`Optional content group not found: ${id}`);
  12715. return true;
  12716. }
  12717. if (this.#groups.get(id).visible) {
  12718. return false;
  12719. }
  12720. }
  12721. return true;
  12722. }
  12723. warn(`Unknown optional content policy ${group.policy}.`);
  12724. return true;
  12725. }
  12726. warn(`Unknown group type ${group.type}.`);
  12727. return true;
  12728. }
  12729. setVisibility(id, visible = true) {
  12730. const group = this.#groups.get(id);
  12731. if (!group) {
  12732. warn(`Optional content group not found: ${id}`);
  12733. return;
  12734. }
  12735. group._setVisible(INTERNAL, !!visible, true);
  12736. this.#cachedGetHash = null;
  12737. }
  12738. setOCGState({
  12739. state,
  12740. preserveRB
  12741. }) {
  12742. let operator;
  12743. for (const elem of state) {
  12744. switch (elem) {
  12745. case "ON":
  12746. case "OFF":
  12747. case "Toggle":
  12748. operator = elem;
  12749. continue;
  12750. }
  12751. const group = this.#groups.get(elem);
  12752. if (!group) {
  12753. continue;
  12754. }
  12755. switch (operator) {
  12756. case "ON":
  12757. group._setVisible(INTERNAL, true);
  12758. break;
  12759. case "OFF":
  12760. group._setVisible(INTERNAL, false);
  12761. break;
  12762. case "Toggle":
  12763. group._setVisible(INTERNAL, !group.visible);
  12764. break;
  12765. }
  12766. }
  12767. this.#cachedGetHash = null;
  12768. }
  12769. get hasInitialVisibility() {
  12770. return this.#initialHash === null || this.getHash() === this.#initialHash;
  12771. }
  12772. getOrder() {
  12773. if (!this.#groups.size) {
  12774. return null;
  12775. }
  12776. if (this.#order) {
  12777. return this.#order.slice();
  12778. }
  12779. return [...this.#groups.keys()];
  12780. }
  12781. getGroups() {
  12782. return this.#groups.size > 0 ? objectFromMap(this.#groups) : null;
  12783. }
  12784. getGroup(id) {
  12785. return this.#groups.get(id) || null;
  12786. }
  12787. getHash() {
  12788. if (this.#cachedGetHash !== null) {
  12789. return this.#cachedGetHash;
  12790. }
  12791. const hash = new MurmurHash3_64();
  12792. for (const [id, group] of this.#groups) {
  12793. hash.update(`${id}:${group.visible}`);
  12794. }
  12795. return this.#cachedGetHash = hash.hexdigest();
  12796. }
  12797. }
  12798. ;// ./src/display/transport_stream.js
  12799. class PDFDataTransportStream {
  12800. constructor(pdfDataRangeTransport, {
  12801. disableRange = false,
  12802. disableStream = false
  12803. }) {
  12804. assert(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');
  12805. const {
  12806. length,
  12807. initialData,
  12808. progressiveDone,
  12809. contentDispositionFilename
  12810. } = pdfDataRangeTransport;
  12811. this._queuedChunks = [];
  12812. this._progressiveDone = progressiveDone;
  12813. this._contentDispositionFilename = contentDispositionFilename;
  12814. if (initialData?.length > 0) {
  12815. const buffer = initialData instanceof Uint8Array && initialData.byteLength === initialData.buffer.byteLength ? initialData.buffer : new Uint8Array(initialData).buffer;
  12816. this._queuedChunks.push(buffer);
  12817. }
  12818. this._pdfDataRangeTransport = pdfDataRangeTransport;
  12819. this._isStreamingSupported = !disableStream;
  12820. this._isRangeSupported = !disableRange;
  12821. this._contentLength = length;
  12822. this._fullRequestReader = null;
  12823. this._rangeReaders = [];
  12824. pdfDataRangeTransport.addRangeListener((begin, chunk) => {
  12825. this._onReceiveData({
  12826. begin,
  12827. chunk
  12828. });
  12829. });
  12830. pdfDataRangeTransport.addProgressListener((loaded, total) => {
  12831. this._onProgress({
  12832. loaded,
  12833. total
  12834. });
  12835. });
  12836. pdfDataRangeTransport.addProgressiveReadListener(chunk => {
  12837. this._onReceiveData({
  12838. chunk
  12839. });
  12840. });
  12841. pdfDataRangeTransport.addProgressiveDoneListener(() => {
  12842. this._onProgressiveDone();
  12843. });
  12844. pdfDataRangeTransport.transportReady();
  12845. }
  12846. _onReceiveData({
  12847. begin,
  12848. chunk
  12849. }) {
  12850. const buffer = chunk instanceof Uint8Array && chunk.byteLength === chunk.buffer.byteLength ? chunk.buffer : new Uint8Array(chunk).buffer;
  12851. if (begin === undefined) {
  12852. if (this._fullRequestReader) {
  12853. this._fullRequestReader._enqueue(buffer);
  12854. } else {
  12855. this._queuedChunks.push(buffer);
  12856. }
  12857. } else {
  12858. const found = this._rangeReaders.some(function (rangeReader) {
  12859. if (rangeReader._begin !== begin) {
  12860. return false;
  12861. }
  12862. rangeReader._enqueue(buffer);
  12863. return true;
  12864. });
  12865. assert(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");
  12866. }
  12867. }
  12868. get _progressiveDataLength() {
  12869. return this._fullRequestReader?._loaded ?? 0;
  12870. }
  12871. _onProgress(evt) {
  12872. if (evt.total === undefined) {
  12873. this._rangeReaders[0]?.onProgress?.({
  12874. loaded: evt.loaded
  12875. });
  12876. } else {
  12877. this._fullRequestReader?.onProgress?.({
  12878. loaded: evt.loaded,
  12879. total: evt.total
  12880. });
  12881. }
  12882. }
  12883. _onProgressiveDone() {
  12884. this._fullRequestReader?.progressiveDone();
  12885. this._progressiveDone = true;
  12886. }
  12887. _removeRangeReader(reader) {
  12888. const i = this._rangeReaders.indexOf(reader);
  12889. if (i >= 0) {
  12890. this._rangeReaders.splice(i, 1);
  12891. }
  12892. }
  12893. getFullReader() {
  12894. assert(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once.");
  12895. const queuedChunks = this._queuedChunks;
  12896. this._queuedChunks = null;
  12897. return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename);
  12898. }
  12899. getRangeReader(begin, end) {
  12900. if (end <= this._progressiveDataLength) {
  12901. return null;
  12902. }
  12903. const reader = new PDFDataTransportStreamRangeReader(this, begin, end);
  12904. this._pdfDataRangeTransport.requestDataRange(begin, end);
  12905. this._rangeReaders.push(reader);
  12906. return reader;
  12907. }
  12908. cancelAllRequests(reason) {
  12909. this._fullRequestReader?.cancel(reason);
  12910. for (const reader of this._rangeReaders.slice(0)) {
  12911. reader.cancel(reason);
  12912. }
  12913. this._pdfDataRangeTransport.abort();
  12914. }
  12915. }
  12916. class PDFDataTransportStreamReader {
  12917. constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) {
  12918. this._stream = stream;
  12919. this._done = progressiveDone || false;
  12920. this._filename = isPdfFile(contentDispositionFilename) ? contentDispositionFilename : null;
  12921. this._queuedChunks = queuedChunks || [];
  12922. this._loaded = 0;
  12923. for (const chunk of this._queuedChunks) {
  12924. this._loaded += chunk.byteLength;
  12925. }
  12926. this._requests = [];
  12927. this._headersReady = Promise.resolve();
  12928. stream._fullRequestReader = this;
  12929. this.onProgress = null;
  12930. }
  12931. _enqueue(chunk) {
  12932. if (this._done) {
  12933. return;
  12934. }
  12935. if (this._requests.length > 0) {
  12936. const requestCapability = this._requests.shift();
  12937. requestCapability.resolve({
  12938. value: chunk,
  12939. done: false
  12940. });
  12941. } else {
  12942. this._queuedChunks.push(chunk);
  12943. }
  12944. this._loaded += chunk.byteLength;
  12945. }
  12946. get headersReady() {
  12947. return this._headersReady;
  12948. }
  12949. get filename() {
  12950. return this._filename;
  12951. }
  12952. get isRangeSupported() {
  12953. return this._stream._isRangeSupported;
  12954. }
  12955. get isStreamingSupported() {
  12956. return this._stream._isStreamingSupported;
  12957. }
  12958. get contentLength() {
  12959. return this._stream._contentLength;
  12960. }
  12961. async read() {
  12962. if (this._queuedChunks.length > 0) {
  12963. const chunk = this._queuedChunks.shift();
  12964. return {
  12965. value: chunk,
  12966. done: false
  12967. };
  12968. }
  12969. if (this._done) {
  12970. return {
  12971. value: undefined,
  12972. done: true
  12973. };
  12974. }
  12975. const requestCapability = Promise.withResolvers();
  12976. this._requests.push(requestCapability);
  12977. return requestCapability.promise;
  12978. }
  12979. cancel(reason) {
  12980. this._done = true;
  12981. for (const requestCapability of this._requests) {
  12982. requestCapability.resolve({
  12983. value: undefined,
  12984. done: true
  12985. });
  12986. }
  12987. this._requests.length = 0;
  12988. }
  12989. progressiveDone() {
  12990. if (this._done) {
  12991. return;
  12992. }
  12993. this._done = true;
  12994. }
  12995. }
  12996. class PDFDataTransportStreamRangeReader {
  12997. constructor(stream, begin, end) {
  12998. this._stream = stream;
  12999. this._begin = begin;
  13000. this._end = end;
  13001. this._queuedChunk = null;
  13002. this._requests = [];
  13003. this._done = false;
  13004. this.onProgress = null;
  13005. }
  13006. _enqueue(chunk) {
  13007. if (this._done) {
  13008. return;
  13009. }
  13010. if (this._requests.length === 0) {
  13011. this._queuedChunk = chunk;
  13012. } else {
  13013. const requestsCapability = this._requests.shift();
  13014. requestsCapability.resolve({
  13015. value: chunk,
  13016. done: false
  13017. });
  13018. for (const requestCapability of this._requests) {
  13019. requestCapability.resolve({
  13020. value: undefined,
  13021. done: true
  13022. });
  13023. }
  13024. this._requests.length = 0;
  13025. }
  13026. this._done = true;
  13027. this._stream._removeRangeReader(this);
  13028. }
  13029. get isStreamingSupported() {
  13030. return false;
  13031. }
  13032. async read() {
  13033. if (this._queuedChunk) {
  13034. const chunk = this._queuedChunk;
  13035. this._queuedChunk = null;
  13036. return {
  13037. value: chunk,
  13038. done: false
  13039. };
  13040. }
  13041. if (this._done) {
  13042. return {
  13043. value: undefined,
  13044. done: true
  13045. };
  13046. }
  13047. const requestCapability = Promise.withResolvers();
  13048. this._requests.push(requestCapability);
  13049. return requestCapability.promise;
  13050. }
  13051. cancel(reason) {
  13052. this._done = true;
  13053. for (const requestCapability of this._requests) {
  13054. requestCapability.resolve({
  13055. value: undefined,
  13056. done: true
  13057. });
  13058. }
  13059. this._requests.length = 0;
  13060. this._stream._removeRangeReader(this);
  13061. }
  13062. }
  13063. ;// ./src/display/content_disposition.js
  13064. function getFilenameFromContentDispositionHeader(contentDisposition) {
  13065. let needsEncodingFixup = true;
  13066. let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
  13067. if (tmp) {
  13068. tmp = tmp[1];
  13069. let filename = rfc2616unquote(tmp);
  13070. filename = unescape(filename);
  13071. filename = rfc5987decode(filename);
  13072. filename = rfc2047decode(filename);
  13073. return fixupEncoding(filename);
  13074. }
  13075. tmp = rfc2231getparam(contentDisposition);
  13076. if (tmp) {
  13077. const filename = rfc2047decode(tmp);
  13078. return fixupEncoding(filename);
  13079. }
  13080. tmp = toParamRegExp("filename", "i").exec(contentDisposition);
  13081. if (tmp) {
  13082. tmp = tmp[1];
  13083. let filename = rfc2616unquote(tmp);
  13084. filename = rfc2047decode(filename);
  13085. return fixupEncoding(filename);
  13086. }
  13087. function toParamRegExp(attributePattern, flags) {
  13088. return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags);
  13089. }
  13090. function textdecode(encoding, value) {
  13091. if (encoding) {
  13092. if (!/^[\x00-\xFF]+$/.test(value)) {
  13093. return value;
  13094. }
  13095. try {
  13096. const decoder = new TextDecoder(encoding, {
  13097. fatal: true
  13098. });
  13099. const buffer = stringToBytes(value);
  13100. value = decoder.decode(buffer);
  13101. needsEncodingFixup = false;
  13102. } catch {}
  13103. }
  13104. return value;
  13105. }
  13106. function fixupEncoding(value) {
  13107. if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
  13108. value = textdecode("utf-8", value);
  13109. if (needsEncodingFixup) {
  13110. value = textdecode("iso-8859-1", value);
  13111. }
  13112. }
  13113. return value;
  13114. }
  13115. function rfc2231getparam(contentDispositionStr) {
  13116. const matches = [];
  13117. let match;
  13118. const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
  13119. while ((match = iter.exec(contentDispositionStr)) !== null) {
  13120. let [, n, quot, part] = match;
  13121. n = parseInt(n, 10);
  13122. if (n in matches) {
  13123. if (n === 0) {
  13124. break;
  13125. }
  13126. continue;
  13127. }
  13128. matches[n] = [quot, part];
  13129. }
  13130. const parts = [];
  13131. for (let n = 0; n < matches.length; ++n) {
  13132. if (!(n in matches)) {
  13133. break;
  13134. }
  13135. let [quot, part] = matches[n];
  13136. part = rfc2616unquote(part);
  13137. if (quot) {
  13138. part = unescape(part);
  13139. if (n === 0) {
  13140. part = rfc5987decode(part);
  13141. }
  13142. }
  13143. parts.push(part);
  13144. }
  13145. return parts.join("");
  13146. }
  13147. function rfc2616unquote(value) {
  13148. if (value.startsWith('"')) {
  13149. const parts = value.slice(1).split('\\"');
  13150. for (let i = 0; i < parts.length; ++i) {
  13151. const quotindex = parts[i].indexOf('"');
  13152. if (quotindex !== -1) {
  13153. parts[i] = parts[i].slice(0, quotindex);
  13154. parts.length = i + 1;
  13155. }
  13156. parts[i] = parts[i].replaceAll(/\\(.)/g, "$1");
  13157. }
  13158. value = parts.join('"');
  13159. }
  13160. return value;
  13161. }
  13162. function rfc5987decode(extvalue) {
  13163. const encodingend = extvalue.indexOf("'");
  13164. if (encodingend === -1) {
  13165. return extvalue;
  13166. }
  13167. const encoding = extvalue.slice(0, encodingend);
  13168. const langvalue = extvalue.slice(encodingend + 1);
  13169. const value = langvalue.replace(/^[^']*'/, "");
  13170. return textdecode(encoding, value);
  13171. }
  13172. function rfc2047decode(value) {
  13173. if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
  13174. return value;
  13175. }
  13176. return value.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) {
  13177. if (encoding === "q" || encoding === "Q") {
  13178. text = text.replaceAll("_", " ");
  13179. text = text.replaceAll(/=([0-9a-fA-F]{2})/g, function (match, hex) {
  13180. return String.fromCharCode(parseInt(hex, 16));
  13181. });
  13182. return textdecode(charset, text);
  13183. }
  13184. try {
  13185. text = atob(text);
  13186. } catch {}
  13187. return textdecode(charset, text);
  13188. });
  13189. }
  13190. return "";
  13191. }
  13192. ;// ./src/display/network_utils.js
  13193. function createHeaders(isHttp, httpHeaders) {
  13194. const headers = new Headers();
  13195. if (!isHttp || !httpHeaders || typeof httpHeaders !== "object") {
  13196. return headers;
  13197. }
  13198. for (const key in httpHeaders) {
  13199. const val = httpHeaders[key];
  13200. if (val !== undefined) {
  13201. headers.append(key, val);
  13202. }
  13203. }
  13204. return headers;
  13205. }
  13206. function validateRangeRequestCapabilities({
  13207. responseHeaders,
  13208. isHttp,
  13209. rangeChunkSize,
  13210. disableRange
  13211. }) {
  13212. const returnValues = {
  13213. allowRangeRequests: false,
  13214. suggestedLength: undefined
  13215. };
  13216. const length = parseInt(responseHeaders.get("Content-Length"), 10);
  13217. if (!Number.isInteger(length)) {
  13218. return returnValues;
  13219. }
  13220. returnValues.suggestedLength = length;
  13221. if (length <= 2 * rangeChunkSize) {
  13222. return returnValues;
  13223. }
  13224. if (disableRange || !isHttp) {
  13225. return returnValues;
  13226. }
  13227. if (responseHeaders.get("Accept-Ranges") !== "bytes") {
  13228. return returnValues;
  13229. }
  13230. const contentEncoding = responseHeaders.get("Content-Encoding") || "identity";
  13231. if (contentEncoding !== "identity") {
  13232. return returnValues;
  13233. }
  13234. returnValues.allowRangeRequests = true;
  13235. return returnValues;
  13236. }
  13237. function extractFilenameFromHeader(responseHeaders) {
  13238. const contentDisposition = responseHeaders.get("Content-Disposition");
  13239. if (contentDisposition) {
  13240. let filename = getFilenameFromContentDispositionHeader(contentDisposition);
  13241. if (filename.includes("%")) {
  13242. try {
  13243. filename = decodeURIComponent(filename);
  13244. } catch {}
  13245. }
  13246. if (isPdfFile(filename)) {
  13247. return filename;
  13248. }
  13249. }
  13250. return null;
  13251. }
  13252. function createResponseStatusError(status, url) {
  13253. if (status === 404 || status === 0 && url.startsWith("file:")) {
  13254. return new MissingPDFException('Missing PDF "' + url + '".');
  13255. }
  13256. return new UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status);
  13257. }
  13258. function validateResponseStatus(status) {
  13259. return status === 200 || status === 206;
  13260. }
  13261. ;// ./src/display/fetch_stream.js
  13262. function createFetchOptions(headers, withCredentials, abortController) {
  13263. return {
  13264. method: "GET",
  13265. headers,
  13266. signal: abortController.signal,
  13267. mode: "cors",
  13268. credentials: withCredentials ? "include" : "same-origin",
  13269. redirect: "follow"
  13270. };
  13271. }
  13272. function getArrayBuffer(val) {
  13273. if (val instanceof Uint8Array) {
  13274. return val.buffer;
  13275. }
  13276. if (val instanceof ArrayBuffer) {
  13277. return val;
  13278. }
  13279. warn(`getArrayBuffer - unexpected data format: ${val}`);
  13280. return new Uint8Array(val).buffer;
  13281. }
  13282. class PDFFetchStream {
  13283. constructor(source) {
  13284. this.source = source;
  13285. this.isHttp = /^https?:/i.test(source.url);
  13286. this.headers = createHeaders(this.isHttp, source.httpHeaders);
  13287. this._fullRequestReader = null;
  13288. this._rangeRequestReaders = [];
  13289. }
  13290. get _progressiveDataLength() {
  13291. return this._fullRequestReader?._loaded ?? 0;
  13292. }
  13293. getFullReader() {
  13294. assert(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once.");
  13295. this._fullRequestReader = new PDFFetchStreamReader(this);
  13296. return this._fullRequestReader;
  13297. }
  13298. getRangeReader(begin, end) {
  13299. if (end <= this._progressiveDataLength) {
  13300. return null;
  13301. }
  13302. const reader = new PDFFetchStreamRangeReader(this, begin, end);
  13303. this._rangeRequestReaders.push(reader);
  13304. return reader;
  13305. }
  13306. cancelAllRequests(reason) {
  13307. this._fullRequestReader?.cancel(reason);
  13308. for (const reader of this._rangeRequestReaders.slice(0)) {
  13309. reader.cancel(reason);
  13310. }
  13311. }
  13312. }
  13313. class PDFFetchStreamReader {
  13314. constructor(stream) {
  13315. this._stream = stream;
  13316. this._reader = null;
  13317. this._loaded = 0;
  13318. this._filename = null;
  13319. const source = stream.source;
  13320. this._withCredentials = source.withCredentials || false;
  13321. this._contentLength = source.length;
  13322. this._headersCapability = Promise.withResolvers();
  13323. this._disableRange = source.disableRange || false;
  13324. this._rangeChunkSize = source.rangeChunkSize;
  13325. if (!this._rangeChunkSize && !this._disableRange) {
  13326. this._disableRange = true;
  13327. }
  13328. this._abortController = new AbortController();
  13329. this._isStreamingSupported = !source.disableStream;
  13330. this._isRangeSupported = !source.disableRange;
  13331. const headers = new Headers(stream.headers);
  13332. const url = source.url;
  13333. fetch(url, createFetchOptions(headers, this._withCredentials, this._abortController)).then(response => {
  13334. if (!validateResponseStatus(response.status)) {
  13335. throw createResponseStatusError(response.status, url);
  13336. }
  13337. this._reader = response.body.getReader();
  13338. this._headersCapability.resolve();
  13339. const responseHeaders = response.headers;
  13340. const {
  13341. allowRangeRequests,
  13342. suggestedLength
  13343. } = validateRangeRequestCapabilities({
  13344. responseHeaders,
  13345. isHttp: stream.isHttp,
  13346. rangeChunkSize: this._rangeChunkSize,
  13347. disableRange: this._disableRange
  13348. });
  13349. this._isRangeSupported = allowRangeRequests;
  13350. this._contentLength = suggestedLength || this._contentLength;
  13351. this._filename = extractFilenameFromHeader(responseHeaders);
  13352. if (!this._isStreamingSupported && this._isRangeSupported) {
  13353. this.cancel(new AbortException("Streaming is disabled."));
  13354. }
  13355. }).catch(this._headersCapability.reject);
  13356. this.onProgress = null;
  13357. }
  13358. get headersReady() {
  13359. return this._headersCapability.promise;
  13360. }
  13361. get filename() {
  13362. return this._filename;
  13363. }
  13364. get contentLength() {
  13365. return this._contentLength;
  13366. }
  13367. get isRangeSupported() {
  13368. return this._isRangeSupported;
  13369. }
  13370. get isStreamingSupported() {
  13371. return this._isStreamingSupported;
  13372. }
  13373. async read() {
  13374. await this._headersCapability.promise;
  13375. const {
  13376. value,
  13377. done
  13378. } = await this._reader.read();
  13379. if (done) {
  13380. return {
  13381. value,
  13382. done
  13383. };
  13384. }
  13385. this._loaded += value.byteLength;
  13386. this.onProgress?.({
  13387. loaded: this._loaded,
  13388. total: this._contentLength
  13389. });
  13390. return {
  13391. value: getArrayBuffer(value),
  13392. done: false
  13393. };
  13394. }
  13395. cancel(reason) {
  13396. this._reader?.cancel(reason);
  13397. this._abortController.abort();
  13398. }
  13399. }
  13400. class PDFFetchStreamRangeReader {
  13401. constructor(stream, begin, end) {
  13402. this._stream = stream;
  13403. this._reader = null;
  13404. this._loaded = 0;
  13405. const source = stream.source;
  13406. this._withCredentials = source.withCredentials || false;
  13407. this._readCapability = Promise.withResolvers();
  13408. this._isStreamingSupported = !source.disableStream;
  13409. this._abortController = new AbortController();
  13410. const headers = new Headers(stream.headers);
  13411. headers.append("Range", `bytes=${begin}-${end - 1}`);
  13412. const url = source.url;
  13413. fetch(url, createFetchOptions(headers, this._withCredentials, this._abortController)).then(response => {
  13414. if (!validateResponseStatus(response.status)) {
  13415. throw createResponseStatusError(response.status, url);
  13416. }
  13417. this._readCapability.resolve();
  13418. this._reader = response.body.getReader();
  13419. }).catch(this._readCapability.reject);
  13420. this.onProgress = null;
  13421. }
  13422. get isStreamingSupported() {
  13423. return this._isStreamingSupported;
  13424. }
  13425. async read() {
  13426. await this._readCapability.promise;
  13427. const {
  13428. value,
  13429. done
  13430. } = await this._reader.read();
  13431. if (done) {
  13432. return {
  13433. value,
  13434. done
  13435. };
  13436. }
  13437. this._loaded += value.byteLength;
  13438. this.onProgress?.({
  13439. loaded: this._loaded
  13440. });
  13441. return {
  13442. value: getArrayBuffer(value),
  13443. done: false
  13444. };
  13445. }
  13446. cancel(reason) {
  13447. this._reader?.cancel(reason);
  13448. this._abortController.abort();
  13449. }
  13450. }
  13451. ;// ./src/display/network.js
  13452. const OK_RESPONSE = 200;
  13453. const PARTIAL_CONTENT_RESPONSE = 206;
  13454. function network_getArrayBuffer(xhr) {
  13455. const data = xhr.response;
  13456. if (typeof data !== "string") {
  13457. return data;
  13458. }
  13459. return stringToBytes(data).buffer;
  13460. }
  13461. class NetworkManager {
  13462. constructor({
  13463. url,
  13464. httpHeaders,
  13465. withCredentials
  13466. }) {
  13467. this.url = url;
  13468. this.isHttp = /^https?:/i.test(url);
  13469. this.headers = createHeaders(this.isHttp, httpHeaders);
  13470. this.withCredentials = withCredentials || false;
  13471. this.currXhrId = 0;
  13472. this.pendingRequests = Object.create(null);
  13473. }
  13474. requestRange(begin, end, listeners) {
  13475. const args = {
  13476. begin,
  13477. end
  13478. };
  13479. for (const prop in listeners) {
  13480. args[prop] = listeners[prop];
  13481. }
  13482. return this.request(args);
  13483. }
  13484. requestFull(listeners) {
  13485. return this.request(listeners);
  13486. }
  13487. request(args) {
  13488. const xhr = new XMLHttpRequest();
  13489. const xhrId = this.currXhrId++;
  13490. const pendingRequest = this.pendingRequests[xhrId] = {
  13491. xhr
  13492. };
  13493. xhr.open("GET", this.url);
  13494. xhr.withCredentials = this.withCredentials;
  13495. for (const [key, val] of this.headers) {
  13496. xhr.setRequestHeader(key, val);
  13497. }
  13498. if (this.isHttp && "begin" in args && "end" in args) {
  13499. xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
  13500. pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
  13501. } else {
  13502. pendingRequest.expectedStatus = OK_RESPONSE;
  13503. }
  13504. xhr.responseType = "arraybuffer";
  13505. if (args.onError) {
  13506. xhr.onerror = function (evt) {
  13507. args.onError(xhr.status);
  13508. };
  13509. }
  13510. xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
  13511. xhr.onprogress = this.onProgress.bind(this, xhrId);
  13512. pendingRequest.onHeadersReceived = args.onHeadersReceived;
  13513. pendingRequest.onDone = args.onDone;
  13514. pendingRequest.onError = args.onError;
  13515. pendingRequest.onProgress = args.onProgress;
  13516. xhr.send(null);
  13517. return xhrId;
  13518. }
  13519. onProgress(xhrId, evt) {
  13520. const pendingRequest = this.pendingRequests[xhrId];
  13521. if (!pendingRequest) {
  13522. return;
  13523. }
  13524. pendingRequest.onProgress?.(evt);
  13525. }
  13526. onStateChange(xhrId, evt) {
  13527. const pendingRequest = this.pendingRequests[xhrId];
  13528. if (!pendingRequest) {
  13529. return;
  13530. }
  13531. const xhr = pendingRequest.xhr;
  13532. if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
  13533. pendingRequest.onHeadersReceived();
  13534. delete pendingRequest.onHeadersReceived;
  13535. }
  13536. if (xhr.readyState !== 4) {
  13537. return;
  13538. }
  13539. if (!(xhrId in this.pendingRequests)) {
  13540. return;
  13541. }
  13542. delete this.pendingRequests[xhrId];
  13543. if (xhr.status === 0 && this.isHttp) {
  13544. pendingRequest.onError?.(xhr.status);
  13545. return;
  13546. }
  13547. const xhrStatus = xhr.status || OK_RESPONSE;
  13548. const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
  13549. if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
  13550. pendingRequest.onError?.(xhr.status);
  13551. return;
  13552. }
  13553. const chunk = network_getArrayBuffer(xhr);
  13554. if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
  13555. const rangeHeader = xhr.getResponseHeader("Content-Range");
  13556. const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
  13557. pendingRequest.onDone({
  13558. begin: parseInt(matches[1], 10),
  13559. chunk
  13560. });
  13561. } else if (chunk) {
  13562. pendingRequest.onDone({
  13563. begin: 0,
  13564. chunk
  13565. });
  13566. } else {
  13567. pendingRequest.onError?.(xhr.status);
  13568. }
  13569. }
  13570. getRequestXhr(xhrId) {
  13571. return this.pendingRequests[xhrId].xhr;
  13572. }
  13573. isPendingRequest(xhrId) {
  13574. return xhrId in this.pendingRequests;
  13575. }
  13576. abortRequest(xhrId) {
  13577. const xhr = this.pendingRequests[xhrId].xhr;
  13578. delete this.pendingRequests[xhrId];
  13579. xhr.abort();
  13580. }
  13581. }
  13582. class PDFNetworkStream {
  13583. constructor(source) {
  13584. this._source = source;
  13585. this._manager = new NetworkManager(source);
  13586. this._rangeChunkSize = source.rangeChunkSize;
  13587. this._fullRequestReader = null;
  13588. this._rangeRequestReaders = [];
  13589. }
  13590. _onRangeRequestReaderClosed(reader) {
  13591. const i = this._rangeRequestReaders.indexOf(reader);
  13592. if (i >= 0) {
  13593. this._rangeRequestReaders.splice(i, 1);
  13594. }
  13595. }
  13596. getFullReader() {
  13597. assert(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
  13598. this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
  13599. return this._fullRequestReader;
  13600. }
  13601. getRangeReader(begin, end) {
  13602. const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
  13603. reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
  13604. this._rangeRequestReaders.push(reader);
  13605. return reader;
  13606. }
  13607. cancelAllRequests(reason) {
  13608. this._fullRequestReader?.cancel(reason);
  13609. for (const reader of this._rangeRequestReaders.slice(0)) {
  13610. reader.cancel(reason);
  13611. }
  13612. }
  13613. }
  13614. class PDFNetworkStreamFullRequestReader {
  13615. constructor(manager, source) {
  13616. this._manager = manager;
  13617. const args = {
  13618. onHeadersReceived: this._onHeadersReceived.bind(this),
  13619. onDone: this._onDone.bind(this),
  13620. onError: this._onError.bind(this),
  13621. onProgress: this._onProgress.bind(this)
  13622. };
  13623. this._url = source.url;
  13624. this._fullRequestId = manager.requestFull(args);
  13625. this._headersCapability = Promise.withResolvers();
  13626. this._disableRange = source.disableRange || false;
  13627. this._contentLength = source.length;
  13628. this._rangeChunkSize = source.rangeChunkSize;
  13629. if (!this._rangeChunkSize && !this._disableRange) {
  13630. this._disableRange = true;
  13631. }
  13632. this._isStreamingSupported = false;
  13633. this._isRangeSupported = false;
  13634. this._cachedChunks = [];
  13635. this._requests = [];
  13636. this._done = false;
  13637. this._storedError = undefined;
  13638. this._filename = null;
  13639. this.onProgress = null;
  13640. }
  13641. _onHeadersReceived() {
  13642. const fullRequestXhrId = this._fullRequestId;
  13643. const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
  13644. const responseHeaders = new Headers(fullRequestXhr.getAllResponseHeaders().trim().split(/[\r\n]+/).map(x => {
  13645. const [key, ...val] = x.split(": ");
  13646. return [key, val.join(": ")];
  13647. }));
  13648. const {
  13649. allowRangeRequests,
  13650. suggestedLength
  13651. } = validateRangeRequestCapabilities({
  13652. responseHeaders,
  13653. isHttp: this._manager.isHttp,
  13654. rangeChunkSize: this._rangeChunkSize,
  13655. disableRange: this._disableRange
  13656. });
  13657. if (allowRangeRequests) {
  13658. this._isRangeSupported = true;
  13659. }
  13660. this._contentLength = suggestedLength || this._contentLength;
  13661. this._filename = extractFilenameFromHeader(responseHeaders);
  13662. if (this._isRangeSupported) {
  13663. this._manager.abortRequest(fullRequestXhrId);
  13664. }
  13665. this._headersCapability.resolve();
  13666. }
  13667. _onDone(data) {
  13668. if (data) {
  13669. if (this._requests.length > 0) {
  13670. const requestCapability = this._requests.shift();
  13671. requestCapability.resolve({
  13672. value: data.chunk,
  13673. done: false
  13674. });
  13675. } else {
  13676. this._cachedChunks.push(data.chunk);
  13677. }
  13678. }
  13679. this._done = true;
  13680. if (this._cachedChunks.length > 0) {
  13681. return;
  13682. }
  13683. for (const requestCapability of this._requests) {
  13684. requestCapability.resolve({
  13685. value: undefined,
  13686. done: true
  13687. });
  13688. }
  13689. this._requests.length = 0;
  13690. }
  13691. _onError(status) {
  13692. this._storedError = createResponseStatusError(status, this._url);
  13693. this._headersCapability.reject(this._storedError);
  13694. for (const requestCapability of this._requests) {
  13695. requestCapability.reject(this._storedError);
  13696. }
  13697. this._requests.length = 0;
  13698. this._cachedChunks.length = 0;
  13699. }
  13700. _onProgress(evt) {
  13701. this.onProgress?.({
  13702. loaded: evt.loaded,
  13703. total: evt.lengthComputable ? evt.total : this._contentLength
  13704. });
  13705. }
  13706. get filename() {
  13707. return this._filename;
  13708. }
  13709. get isRangeSupported() {
  13710. return this._isRangeSupported;
  13711. }
  13712. get isStreamingSupported() {
  13713. return this._isStreamingSupported;
  13714. }
  13715. get contentLength() {
  13716. return this._contentLength;
  13717. }
  13718. get headersReady() {
  13719. return this._headersCapability.promise;
  13720. }
  13721. async read() {
  13722. if (this._storedError) {
  13723. throw this._storedError;
  13724. }
  13725. if (this._cachedChunks.length > 0) {
  13726. const chunk = this._cachedChunks.shift();
  13727. return {
  13728. value: chunk,
  13729. done: false
  13730. };
  13731. }
  13732. if (this._done) {
  13733. return {
  13734. value: undefined,
  13735. done: true
  13736. };
  13737. }
  13738. const requestCapability = Promise.withResolvers();
  13739. this._requests.push(requestCapability);
  13740. return requestCapability.promise;
  13741. }
  13742. cancel(reason) {
  13743. this._done = true;
  13744. this._headersCapability.reject(reason);
  13745. for (const requestCapability of this._requests) {
  13746. requestCapability.resolve({
  13747. value: undefined,
  13748. done: true
  13749. });
  13750. }
  13751. this._requests.length = 0;
  13752. if (this._manager.isPendingRequest(this._fullRequestId)) {
  13753. this._manager.abortRequest(this._fullRequestId);
  13754. }
  13755. this._fullRequestReader = null;
  13756. }
  13757. }
  13758. class PDFNetworkStreamRangeRequestReader {
  13759. constructor(manager, begin, end) {
  13760. this._manager = manager;
  13761. const args = {
  13762. onDone: this._onDone.bind(this),
  13763. onError: this._onError.bind(this),
  13764. onProgress: this._onProgress.bind(this)
  13765. };
  13766. this._url = manager.url;
  13767. this._requestId = manager.requestRange(begin, end, args);
  13768. this._requests = [];
  13769. this._queuedChunk = null;
  13770. this._done = false;
  13771. this._storedError = undefined;
  13772. this.onProgress = null;
  13773. this.onClosed = null;
  13774. }
  13775. _close() {
  13776. this.onClosed?.(this);
  13777. }
  13778. _onDone(data) {
  13779. const chunk = data.chunk;
  13780. if (this._requests.length > 0) {
  13781. const requestCapability = this._requests.shift();
  13782. requestCapability.resolve({
  13783. value: chunk,
  13784. done: false
  13785. });
  13786. } else {
  13787. this._queuedChunk = chunk;
  13788. }
  13789. this._done = true;
  13790. for (const requestCapability of this._requests) {
  13791. requestCapability.resolve({
  13792. value: undefined,
  13793. done: true
  13794. });
  13795. }
  13796. this._requests.length = 0;
  13797. this._close();
  13798. }
  13799. _onError(status) {
  13800. this._storedError = createResponseStatusError(status, this._url);
  13801. for (const requestCapability of this._requests) {
  13802. requestCapability.reject(this._storedError);
  13803. }
  13804. this._requests.length = 0;
  13805. this._queuedChunk = null;
  13806. }
  13807. _onProgress(evt) {
  13808. if (!this.isStreamingSupported) {
  13809. this.onProgress?.({
  13810. loaded: evt.loaded
  13811. });
  13812. }
  13813. }
  13814. get isStreamingSupported() {
  13815. return false;
  13816. }
  13817. async read() {
  13818. if (this._storedError) {
  13819. throw this._storedError;
  13820. }
  13821. if (this._queuedChunk !== null) {
  13822. const chunk = this._queuedChunk;
  13823. this._queuedChunk = null;
  13824. return {
  13825. value: chunk,
  13826. done: false
  13827. };
  13828. }
  13829. if (this._done) {
  13830. return {
  13831. value: undefined,
  13832. done: true
  13833. };
  13834. }
  13835. const requestCapability = Promise.withResolvers();
  13836. this._requests.push(requestCapability);
  13837. return requestCapability.promise;
  13838. }
  13839. cancel(reason) {
  13840. this._done = true;
  13841. for (const requestCapability of this._requests) {
  13842. requestCapability.resolve({
  13843. value: undefined,
  13844. done: true
  13845. });
  13846. }
  13847. this._requests.length = 0;
  13848. if (this._manager.isPendingRequest(this._requestId)) {
  13849. this._manager.abortRequest(this._requestId);
  13850. }
  13851. this._close();
  13852. }
  13853. }
  13854. ;// ./src/display/node_stream.js
  13855. const urlRegex = /^[a-z][a-z0-9\-+.]+:/i;
  13856. function parseUrlOrPath(sourceUrl) {
  13857. if (urlRegex.test(sourceUrl)) {
  13858. return new URL(sourceUrl);
  13859. }
  13860. const url = NodePackages.get("url");
  13861. return new URL(url.pathToFileURL(sourceUrl));
  13862. }
  13863. function createRequest(url, headers, callback) {
  13864. if (url.protocol === "http:") {
  13865. const http = NodePackages.get("http");
  13866. return http.request(url, {
  13867. headers
  13868. }, callback);
  13869. }
  13870. const https = NodePackages.get("https");
  13871. return https.request(url, {
  13872. headers
  13873. }, callback);
  13874. }
  13875. class PDFNodeStream {
  13876. constructor(source) {
  13877. this.source = source;
  13878. this.url = parseUrlOrPath(source.url);
  13879. this.isHttp = this.url.protocol === "http:" || this.url.protocol === "https:";
  13880. this.isFsUrl = this.url.protocol === "file:";
  13881. this.headers = createHeaders(this.isHttp, source.httpHeaders);
  13882. this._fullRequestReader = null;
  13883. this._rangeRequestReaders = [];
  13884. }
  13885. get _progressiveDataLength() {
  13886. return this._fullRequestReader?._loaded ?? 0;
  13887. }
  13888. getFullReader() {
  13889. assert(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
  13890. this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
  13891. return this._fullRequestReader;
  13892. }
  13893. getRangeReader(start, end) {
  13894. if (end <= this._progressiveDataLength) {
  13895. return null;
  13896. }
  13897. const rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end);
  13898. this._rangeRequestReaders.push(rangeReader);
  13899. return rangeReader;
  13900. }
  13901. cancelAllRequests(reason) {
  13902. this._fullRequestReader?.cancel(reason);
  13903. for (const reader of this._rangeRequestReaders.slice(0)) {
  13904. reader.cancel(reason);
  13905. }
  13906. }
  13907. }
  13908. class BaseFullReader {
  13909. constructor(stream) {
  13910. this._url = stream.url;
  13911. this._done = false;
  13912. this._storedError = null;
  13913. this.onProgress = null;
  13914. const source = stream.source;
  13915. this._contentLength = source.length;
  13916. this._loaded = 0;
  13917. this._filename = null;
  13918. this._disableRange = source.disableRange || false;
  13919. this._rangeChunkSize = source.rangeChunkSize;
  13920. if (!this._rangeChunkSize && !this._disableRange) {
  13921. this._disableRange = true;
  13922. }
  13923. this._isStreamingSupported = !source.disableStream;
  13924. this._isRangeSupported = !source.disableRange;
  13925. this._readableStream = null;
  13926. this._readCapability = Promise.withResolvers();
  13927. this._headersCapability = Promise.withResolvers();
  13928. }
  13929. get headersReady() {
  13930. return this._headersCapability.promise;
  13931. }
  13932. get filename() {
  13933. return this._filename;
  13934. }
  13935. get contentLength() {
  13936. return this._contentLength;
  13937. }
  13938. get isRangeSupported() {
  13939. return this._isRangeSupported;
  13940. }
  13941. get isStreamingSupported() {
  13942. return this._isStreamingSupported;
  13943. }
  13944. async read() {
  13945. await this._readCapability.promise;
  13946. if (this._done) {
  13947. return {
  13948. value: undefined,
  13949. done: true
  13950. };
  13951. }
  13952. if (this._storedError) {
  13953. throw this._storedError;
  13954. }
  13955. const chunk = this._readableStream.read();
  13956. if (chunk === null) {
  13957. this._readCapability = Promise.withResolvers();
  13958. return this.read();
  13959. }
  13960. this._loaded += chunk.length;
  13961. this.onProgress?.({
  13962. loaded: this._loaded,
  13963. total: this._contentLength
  13964. });
  13965. const buffer = new Uint8Array(chunk).buffer;
  13966. return {
  13967. value: buffer,
  13968. done: false
  13969. };
  13970. }
  13971. cancel(reason) {
  13972. if (!this._readableStream) {
  13973. this._error(reason);
  13974. return;
  13975. }
  13976. this._readableStream.destroy(reason);
  13977. }
  13978. _error(reason) {
  13979. this._storedError = reason;
  13980. this._readCapability.resolve();
  13981. }
  13982. _setReadableStream(readableStream) {
  13983. this._readableStream = readableStream;
  13984. readableStream.on("readable", () => {
  13985. this._readCapability.resolve();
  13986. });
  13987. readableStream.on("end", () => {
  13988. readableStream.destroy();
  13989. this._done = true;
  13990. this._readCapability.resolve();
  13991. });
  13992. readableStream.on("error", reason => {
  13993. this._error(reason);
  13994. });
  13995. if (!this._isStreamingSupported && this._isRangeSupported) {
  13996. this._error(new AbortException("streaming is disabled"));
  13997. }
  13998. if (this._storedError) {
  13999. this._readableStream.destroy(this._storedError);
  14000. }
  14001. }
  14002. }
  14003. class BaseRangeReader {
  14004. constructor(stream) {
  14005. this._url = stream.url;
  14006. this._done = false;
  14007. this._storedError = null;
  14008. this.onProgress = null;
  14009. this._loaded = 0;
  14010. this._readableStream = null;
  14011. this._readCapability = Promise.withResolvers();
  14012. const source = stream.source;
  14013. this._isStreamingSupported = !source.disableStream;
  14014. }
  14015. get isStreamingSupported() {
  14016. return this._isStreamingSupported;
  14017. }
  14018. async read() {
  14019. await this._readCapability.promise;
  14020. if (this._done) {
  14021. return {
  14022. value: undefined,
  14023. done: true
  14024. };
  14025. }
  14026. if (this._storedError) {
  14027. throw this._storedError;
  14028. }
  14029. const chunk = this._readableStream.read();
  14030. if (chunk === null) {
  14031. this._readCapability = Promise.withResolvers();
  14032. return this.read();
  14033. }
  14034. this._loaded += chunk.length;
  14035. this.onProgress?.({
  14036. loaded: this._loaded
  14037. });
  14038. const buffer = new Uint8Array(chunk).buffer;
  14039. return {
  14040. value: buffer,
  14041. done: false
  14042. };
  14043. }
  14044. cancel(reason) {
  14045. if (!this._readableStream) {
  14046. this._error(reason);
  14047. return;
  14048. }
  14049. this._readableStream.destroy(reason);
  14050. }
  14051. _error(reason) {
  14052. this._storedError = reason;
  14053. this._readCapability.resolve();
  14054. }
  14055. _setReadableStream(readableStream) {
  14056. this._readableStream = readableStream;
  14057. readableStream.on("readable", () => {
  14058. this._readCapability.resolve();
  14059. });
  14060. readableStream.on("end", () => {
  14061. readableStream.destroy();
  14062. this._done = true;
  14063. this._readCapability.resolve();
  14064. });
  14065. readableStream.on("error", reason => {
  14066. this._error(reason);
  14067. });
  14068. if (this._storedError) {
  14069. this._readableStream.destroy(this._storedError);
  14070. }
  14071. }
  14072. }
  14073. class PDFNodeStreamFullReader extends BaseFullReader {
  14074. constructor(stream) {
  14075. super(stream);
  14076. const headers = Object.fromEntries(stream.headers);
  14077. const handleResponse = response => {
  14078. if (response.statusCode === 404) {
  14079. const error = new MissingPDFException(`Missing PDF "${this._url}".`);
  14080. this._storedError = error;
  14081. this._headersCapability.reject(error);
  14082. return;
  14083. }
  14084. this._headersCapability.resolve();
  14085. this._setReadableStream(response);
  14086. const responseHeaders = new Headers(this._readableStream.headers);
  14087. const {
  14088. allowRangeRequests,
  14089. suggestedLength
  14090. } = validateRangeRequestCapabilities({
  14091. responseHeaders,
  14092. isHttp: stream.isHttp,
  14093. rangeChunkSize: this._rangeChunkSize,
  14094. disableRange: this._disableRange
  14095. });
  14096. this._isRangeSupported = allowRangeRequests;
  14097. this._contentLength = suggestedLength || this._contentLength;
  14098. this._filename = extractFilenameFromHeader(responseHeaders);
  14099. };
  14100. this._request = createRequest(this._url, headers, handleResponse);
  14101. this._request.on("error", reason => {
  14102. this._storedError = reason;
  14103. this._headersCapability.reject(reason);
  14104. });
  14105. this._request.end();
  14106. }
  14107. }
  14108. class PDFNodeStreamRangeReader extends BaseRangeReader {
  14109. constructor(stream, start, end) {
  14110. super(stream);
  14111. const headers = Object.fromEntries(stream.headers);
  14112. headers.Range = `bytes=${start}-${end - 1}`;
  14113. const handleResponse = response => {
  14114. if (response.statusCode === 404) {
  14115. const error = new MissingPDFException(`Missing PDF "${this._url}".`);
  14116. this._storedError = error;
  14117. return;
  14118. }
  14119. this._setReadableStream(response);
  14120. };
  14121. this._request = createRequest(this._url, headers, handleResponse);
  14122. this._request.on("error", reason => {
  14123. this._storedError = reason;
  14124. });
  14125. this._request.end();
  14126. }
  14127. }
  14128. class PDFNodeStreamFsFullReader extends BaseFullReader {
  14129. constructor(stream) {
  14130. super(stream);
  14131. const fs = NodePackages.get("fs");
  14132. fs.promises.lstat(this._url).then(stat => {
  14133. this._contentLength = stat.size;
  14134. this._setReadableStream(fs.createReadStream(this._url));
  14135. this._headersCapability.resolve();
  14136. }, error => {
  14137. if (error.code === "ENOENT") {
  14138. error = new MissingPDFException(`Missing PDF "${this._url}".`);
  14139. }
  14140. this._storedError = error;
  14141. this._headersCapability.reject(error);
  14142. });
  14143. }
  14144. }
  14145. class PDFNodeStreamFsRangeReader extends BaseRangeReader {
  14146. constructor(stream, start, end) {
  14147. super(stream);
  14148. const fs = NodePackages.get("fs");
  14149. this._setReadableStream(fs.createReadStream(this._url, {
  14150. start,
  14151. end: end - 1
  14152. }));
  14153. }
  14154. }
  14155. ;// ./src/display/text_layer.js
  14156. const MAX_TEXT_DIVS_TO_RENDER = 100000;
  14157. const DEFAULT_FONT_SIZE = 30;
  14158. const DEFAULT_FONT_ASCENT = 0.8;
  14159. class TextLayer {
  14160. #capability = Promise.withResolvers();
  14161. #container = null;
  14162. #disableProcessItems = false;
  14163. #fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
  14164. #lang = null;
  14165. #layoutTextParams = null;
  14166. #pageHeight = 0;
  14167. #pageWidth = 0;
  14168. #reader = null;
  14169. #rootContainer = null;
  14170. #rotation = 0;
  14171. #scale = 0;
  14172. #styleCache = Object.create(null);
  14173. #textContentItemsStr = [];
  14174. #textContentSource = null;
  14175. #textDivs = [];
  14176. #textDivProperties = new WeakMap();
  14177. #transform = null;
  14178. static #ascentCache = new Map();
  14179. static #canvasContexts = new Map();
  14180. static #canvasCtxFonts = new WeakMap();
  14181. static #minFontSize = null;
  14182. static #pendingTextLayers = new Set();
  14183. constructor({
  14184. textContentSource,
  14185. container,
  14186. viewport
  14187. }) {
  14188. if (textContentSource instanceof ReadableStream) {
  14189. this.#textContentSource = textContentSource;
  14190. } else if (typeof textContentSource === "object") {
  14191. this.#textContentSource = new ReadableStream({
  14192. start(controller) {
  14193. controller.enqueue(textContentSource);
  14194. controller.close();
  14195. }
  14196. });
  14197. } else {
  14198. throw new Error('No "textContentSource" parameter specified.');
  14199. }
  14200. this.#container = this.#rootContainer = container;
  14201. this.#scale = viewport.scale * (globalThis.devicePixelRatio || 1);
  14202. this.#rotation = viewport.rotation;
  14203. this.#layoutTextParams = {
  14204. div: null,
  14205. properties: null,
  14206. ctx: null
  14207. };
  14208. const {
  14209. pageWidth,
  14210. pageHeight,
  14211. pageX,
  14212. pageY
  14213. } = viewport.rawDims;
  14214. this.#transform = [1, 0, 0, -1, -pageX, pageY + pageHeight];
  14215. this.#pageWidth = pageWidth;
  14216. this.#pageHeight = pageHeight;
  14217. TextLayer.#ensureMinFontSizeComputed();
  14218. setLayerDimensions(container, viewport);
  14219. this.#capability.promise.finally(() => {
  14220. TextLayer.#pendingTextLayers.delete(this);
  14221. this.#layoutTextParams = null;
  14222. this.#styleCache = null;
  14223. }).catch(() => {});
  14224. }
  14225. static get fontFamilyMap() {
  14226. const {
  14227. isWindows,
  14228. isFirefox
  14229. } = util_FeatureTest.platform;
  14230. return shadow(this, "fontFamilyMap", new Map([["sans-serif", `${isWindows && isFirefox ? "Calibri, " : ""}sans-serif`], ["monospace", `${isWindows && isFirefox ? "Lucida Console, " : ""}monospace`]]));
  14231. }
  14232. render() {
  14233. const pump = () => {
  14234. this.#reader.read().then(({
  14235. value,
  14236. done
  14237. }) => {
  14238. if (done) {
  14239. this.#capability.resolve();
  14240. return;
  14241. }
  14242. this.#lang ??= value.lang;
  14243. Object.assign(this.#styleCache, value.styles);
  14244. this.#processItems(value.items);
  14245. pump();
  14246. }, this.#capability.reject);
  14247. };
  14248. this.#reader = this.#textContentSource.getReader();
  14249. TextLayer.#pendingTextLayers.add(this);
  14250. pump();
  14251. return this.#capability.promise;
  14252. }
  14253. update({
  14254. viewport,
  14255. onBefore = null
  14256. }) {
  14257. const scale = viewport.scale * (globalThis.devicePixelRatio || 1);
  14258. const rotation = viewport.rotation;
  14259. if (rotation !== this.#rotation) {
  14260. onBefore?.();
  14261. this.#rotation = rotation;
  14262. setLayerDimensions(this.#rootContainer, {
  14263. rotation
  14264. });
  14265. }
  14266. if (scale !== this.#scale) {
  14267. onBefore?.();
  14268. this.#scale = scale;
  14269. const params = {
  14270. div: null,
  14271. properties: null,
  14272. ctx: TextLayer.#getCtx(this.#lang)
  14273. };
  14274. for (const div of this.#textDivs) {
  14275. params.properties = this.#textDivProperties.get(div);
  14276. params.div = div;
  14277. this.#layout(params);
  14278. }
  14279. }
  14280. }
  14281. cancel() {
  14282. const abortEx = new AbortException("TextLayer task cancelled.");
  14283. this.#reader?.cancel(abortEx).catch(() => {});
  14284. this.#reader = null;
  14285. this.#capability.reject(abortEx);
  14286. }
  14287. get textDivs() {
  14288. return this.#textDivs;
  14289. }
  14290. get textContentItemsStr() {
  14291. return this.#textContentItemsStr;
  14292. }
  14293. #processItems(items) {
  14294. if (this.#disableProcessItems) {
  14295. return;
  14296. }
  14297. this.#layoutTextParams.ctx ??= TextLayer.#getCtx(this.#lang);
  14298. const textDivs = this.#textDivs,
  14299. textContentItemsStr = this.#textContentItemsStr;
  14300. for (const item of items) {
  14301. if (textDivs.length > MAX_TEXT_DIVS_TO_RENDER) {
  14302. warn("Ignoring additional textDivs for performance reasons.");
  14303. this.#disableProcessItems = true;
  14304. return;
  14305. }
  14306. if (item.str === undefined) {
  14307. if (item.type === "beginMarkedContentProps" || item.type === "beginMarkedContent") {
  14308. const parent = this.#container;
  14309. this.#container = document.createElement("span");
  14310. this.#container.classList.add("markedContent");
  14311. if (item.id !== null) {
  14312. this.#container.setAttribute("id", `${item.id}`);
  14313. }
  14314. parent.append(this.#container);
  14315. } else if (item.type === "endMarkedContent") {
  14316. this.#container = this.#container.parentNode;
  14317. }
  14318. continue;
  14319. }
  14320. textContentItemsStr.push(item.str);
  14321. this.#appendText(item);
  14322. }
  14323. }
  14324. #appendText(geom) {
  14325. const textDiv = document.createElement("span");
  14326. const textDivProperties = {
  14327. angle: 0,
  14328. canvasWidth: 0,
  14329. hasText: geom.str !== "",
  14330. hasEOL: geom.hasEOL,
  14331. fontSize: 0
  14332. };
  14333. this.#textDivs.push(textDiv);
  14334. const tx = Util.transform(this.#transform, geom.transform);
  14335. let angle = Math.atan2(tx[1], tx[0]);
  14336. const style = this.#styleCache[geom.fontName];
  14337. if (style.vertical) {
  14338. angle += Math.PI / 2;
  14339. }
  14340. let fontFamily = this.#fontInspectorEnabled && style.fontSubstitution || style.fontFamily;
  14341. fontFamily = TextLayer.fontFamilyMap.get(fontFamily) || fontFamily;
  14342. const fontHeight = Math.hypot(tx[2], tx[3]);
  14343. const fontAscent = fontHeight * TextLayer.#getAscent(fontFamily, this.#lang);
  14344. let left, top;
  14345. if (angle === 0) {
  14346. left = tx[4];
  14347. top = tx[5] - fontAscent;
  14348. } else {
  14349. left = tx[4] + fontAscent * Math.sin(angle);
  14350. top = tx[5] - fontAscent * Math.cos(angle);
  14351. }
  14352. const scaleFactorStr = "calc(var(--scale-factor)*";
  14353. const divStyle = textDiv.style;
  14354. if (this.#container === this.#rootContainer) {
  14355. divStyle.left = `${(100 * left / this.#pageWidth).toFixed(2)}%`;
  14356. divStyle.top = `${(100 * top / this.#pageHeight).toFixed(2)}%`;
  14357. } else {
  14358. divStyle.left = `${scaleFactorStr}${left.toFixed(2)}px)`;
  14359. divStyle.top = `${scaleFactorStr}${top.toFixed(2)}px)`;
  14360. }
  14361. divStyle.fontSize = `${scaleFactorStr}${(TextLayer.#minFontSize * fontHeight).toFixed(2)}px)`;
  14362. divStyle.fontFamily = fontFamily;
  14363. textDivProperties.fontSize = fontHeight;
  14364. textDiv.setAttribute("role", "presentation");
  14365. textDiv.textContent = geom.str;
  14366. textDiv.dir = geom.dir;
  14367. if (this.#fontInspectorEnabled) {
  14368. textDiv.dataset.fontName = style.fontSubstitutionLoadedName || geom.fontName;
  14369. }
  14370. if (angle !== 0) {
  14371. textDivProperties.angle = angle * (180 / Math.PI);
  14372. }
  14373. let shouldScaleText = false;
  14374. if (geom.str.length > 1) {
  14375. shouldScaleText = true;
  14376. } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) {
  14377. const absScaleX = Math.abs(geom.transform[0]),
  14378. absScaleY = Math.abs(geom.transform[3]);
  14379. if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {
  14380. shouldScaleText = true;
  14381. }
  14382. }
  14383. if (shouldScaleText) {
  14384. textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width;
  14385. }
  14386. this.#textDivProperties.set(textDiv, textDivProperties);
  14387. this.#layoutTextParams.div = textDiv;
  14388. this.#layoutTextParams.properties = textDivProperties;
  14389. this.#layout(this.#layoutTextParams);
  14390. if (textDivProperties.hasText) {
  14391. this.#container.append(textDiv);
  14392. }
  14393. if (textDivProperties.hasEOL) {
  14394. const br = document.createElement("br");
  14395. br.setAttribute("role", "presentation");
  14396. this.#container.append(br);
  14397. }
  14398. }
  14399. #layout(params) {
  14400. const {
  14401. div,
  14402. properties,
  14403. ctx
  14404. } = params;
  14405. const {
  14406. style
  14407. } = div;
  14408. let transform = "";
  14409. if (TextLayer.#minFontSize > 1) {
  14410. transform = `scale(${1 / TextLayer.#minFontSize})`;
  14411. }
  14412. if (properties.canvasWidth !== 0 && properties.hasText) {
  14413. const {
  14414. fontFamily
  14415. } = style;
  14416. const {
  14417. canvasWidth,
  14418. fontSize
  14419. } = properties;
  14420. TextLayer.#ensureCtxFont(ctx, fontSize * this.#scale, fontFamily);
  14421. const {
  14422. width
  14423. } = ctx.measureText(div.textContent);
  14424. if (width > 0) {
  14425. transform = `scaleX(${canvasWidth * this.#scale / width}) ${transform}`;
  14426. }
  14427. }
  14428. if (properties.angle !== 0) {
  14429. transform = `rotate(${properties.angle}deg) ${transform}`;
  14430. }
  14431. if (transform.length > 0) {
  14432. style.transform = transform;
  14433. }
  14434. }
  14435. static cleanup() {
  14436. if (this.#pendingTextLayers.size > 0) {
  14437. return;
  14438. }
  14439. this.#ascentCache.clear();
  14440. for (const {
  14441. canvas
  14442. } of this.#canvasContexts.values()) {
  14443. canvas.remove();
  14444. }
  14445. this.#canvasContexts.clear();
  14446. }
  14447. static #getCtx(lang = null) {
  14448. let ctx = this.#canvasContexts.get(lang ||= "");
  14449. if (!ctx) {
  14450. const canvas = document.createElement("canvas");
  14451. canvas.className = "hiddenCanvasElement";
  14452. canvas.lang = lang;
  14453. document.body.append(canvas);
  14454. ctx = canvas.getContext("2d", {
  14455. alpha: false,
  14456. willReadFrequently: true
  14457. });
  14458. this.#canvasContexts.set(lang, ctx);
  14459. this.#canvasCtxFonts.set(ctx, {
  14460. size: 0,
  14461. family: ""
  14462. });
  14463. }
  14464. return ctx;
  14465. }
  14466. static #ensureCtxFont(ctx, size, family) {
  14467. const cached = this.#canvasCtxFonts.get(ctx);
  14468. if (size === cached.size && family === cached.family) {
  14469. return;
  14470. }
  14471. ctx.font = `${size}px ${family}`;
  14472. cached.size = size;
  14473. cached.family = family;
  14474. }
  14475. static #ensureMinFontSizeComputed() {
  14476. if (this.#minFontSize !== null) {
  14477. return;
  14478. }
  14479. const div = document.createElement("div");
  14480. div.style.opacity = 0;
  14481. div.style.lineHeight = 1;
  14482. div.style.fontSize = "1px";
  14483. div.style.position = "absolute";
  14484. div.textContent = "X";
  14485. document.body.append(div);
  14486. this.#minFontSize = div.getBoundingClientRect().height;
  14487. div.remove();
  14488. }
  14489. static #getAscent(fontFamily, lang) {
  14490. const cachedAscent = this.#ascentCache.get(fontFamily);
  14491. if (cachedAscent) {
  14492. return cachedAscent;
  14493. }
  14494. const ctx = this.#getCtx(lang);
  14495. ctx.canvas.width = ctx.canvas.height = DEFAULT_FONT_SIZE;
  14496. this.#ensureCtxFont(ctx, DEFAULT_FONT_SIZE, fontFamily);
  14497. const metrics = ctx.measureText("");
  14498. let ascent = metrics.fontBoundingBoxAscent;
  14499. let descent = Math.abs(metrics.fontBoundingBoxDescent);
  14500. if (ascent) {
  14501. const ratio = ascent / (ascent + descent);
  14502. this.#ascentCache.set(fontFamily, ratio);
  14503. ctx.canvas.width = ctx.canvas.height = 0;
  14504. return ratio;
  14505. }
  14506. ctx.strokeStyle = "red";
  14507. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  14508. ctx.strokeText("g", 0, 0);
  14509. let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  14510. descent = 0;
  14511. for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) {
  14512. if (pixels[i] > 0) {
  14513. descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE);
  14514. break;
  14515. }
  14516. }
  14517. ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  14518. ctx.strokeText("A", 0, DEFAULT_FONT_SIZE);
  14519. pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  14520. ascent = 0;
  14521. for (let i = 0, ii = pixels.length; i < ii; i += 4) {
  14522. if (pixels[i] > 0) {
  14523. ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE);
  14524. break;
  14525. }
  14526. }
  14527. ctx.canvas.width = ctx.canvas.height = 0;
  14528. const ratio = ascent ? ascent / (ascent + descent) : DEFAULT_FONT_ASCENT;
  14529. this.#ascentCache.set(fontFamily, ratio);
  14530. return ratio;
  14531. }
  14532. }
  14533. ;// ./src/display/xfa_text.js
  14534. class XfaText {
  14535. static textContent(xfa) {
  14536. const items = [];
  14537. const output = {
  14538. items,
  14539. styles: Object.create(null)
  14540. };
  14541. function walk(node) {
  14542. if (!node) {
  14543. return;
  14544. }
  14545. let str = null;
  14546. const name = node.name;
  14547. if (name === "#text") {
  14548. str = node.value;
  14549. } else if (!XfaText.shouldBuildText(name)) {
  14550. return;
  14551. } else if (node?.attributes?.textContent) {
  14552. str = node.attributes.textContent;
  14553. } else if (node.value) {
  14554. str = node.value;
  14555. }
  14556. if (str !== null) {
  14557. items.push({
  14558. str
  14559. });
  14560. }
  14561. if (!node.children) {
  14562. return;
  14563. }
  14564. for (const child of node.children) {
  14565. walk(child);
  14566. }
  14567. }
  14568. walk(xfa);
  14569. return output;
  14570. }
  14571. static shouldBuildText(name) {
  14572. return !(name === "textarea" || name === "input" || name === "option" || name === "select");
  14573. }
  14574. }
  14575. ;// ./src/display/api.js
  14576. const DEFAULT_RANGE_CHUNK_SIZE = 65536;
  14577. const RENDERING_CANCELLED_TIMEOUT = 100;
  14578. const DELAYED_CLEANUP_TIMEOUT = 5000;
  14579. const DefaultCanvasFactory = isNodeJS ? NodeCanvasFactory : DOMCanvasFactory;
  14580. const DefaultCMapReaderFactory = isNodeJS ? NodeCMapReaderFactory : DOMCMapReaderFactory;
  14581. const DefaultFilterFactory = isNodeJS ? NodeFilterFactory : DOMFilterFactory;
  14582. const DefaultStandardFontDataFactory = isNodeJS ? NodeStandardFontDataFactory : DOMStandardFontDataFactory;
  14583. function getDocument(src = {}) {
  14584. if (typeof src === "string" || src instanceof URL) {
  14585. src = {
  14586. url: src
  14587. };
  14588. } else if (src instanceof ArrayBuffer || ArrayBuffer.isView(src)) {
  14589. src = {
  14590. data: src
  14591. };
  14592. }
  14593. const task = new PDFDocumentLoadingTask();
  14594. const {
  14595. docId
  14596. } = task;
  14597. const url = src.url ? getUrlProp(src.url) : null;
  14598. const data = src.data ? getDataProp(src.data) : null;
  14599. const httpHeaders = src.httpHeaders || null;
  14600. const withCredentials = src.withCredentials === true;
  14601. const password = src.password ?? null;
  14602. const rangeTransport = src.range instanceof PDFDataRangeTransport ? src.range : null;
  14603. const rangeChunkSize = Number.isInteger(src.rangeChunkSize) && src.rangeChunkSize > 0 ? src.rangeChunkSize : DEFAULT_RANGE_CHUNK_SIZE;
  14604. let worker = src.worker instanceof PDFWorker ? src.worker : null;
  14605. const verbosity = src.verbosity;
  14606. const docBaseUrl = typeof src.docBaseUrl === "string" && !isDataScheme(src.docBaseUrl) ? src.docBaseUrl : null;
  14607. const cMapUrl = typeof src.cMapUrl === "string" ? src.cMapUrl : null;
  14608. const cMapPacked = src.cMapPacked !== false;
  14609. const CMapReaderFactory = src.CMapReaderFactory || DefaultCMapReaderFactory;
  14610. const standardFontDataUrl = typeof src.standardFontDataUrl === "string" ? src.standardFontDataUrl : null;
  14611. const StandardFontDataFactory = src.StandardFontDataFactory || DefaultStandardFontDataFactory;
  14612. const ignoreErrors = src.stopAtErrors !== true;
  14613. const maxImageSize = Number.isInteger(src.maxImageSize) && src.maxImageSize > -1 ? src.maxImageSize : -1;
  14614. const isEvalSupported = src.isEvalSupported !== false;
  14615. const isOffscreenCanvasSupported = typeof src.isOffscreenCanvasSupported === "boolean" ? src.isOffscreenCanvasSupported : !isNodeJS;
  14616. const canvasMaxAreaInBytes = Number.isInteger(src.canvasMaxAreaInBytes) ? src.canvasMaxAreaInBytes : -1;
  14617. const disableFontFace = typeof src.disableFontFace === "boolean" ? src.disableFontFace : isNodeJS;
  14618. const fontExtraProperties = src.fontExtraProperties === true;
  14619. const enableXfa = src.enableXfa === true;
  14620. const ownerDocument = src.ownerDocument || globalThis.document;
  14621. const disableRange = src.disableRange === true;
  14622. const disableStream = src.disableStream === true;
  14623. const disableAutoFetch = src.disableAutoFetch === true;
  14624. const pdfBug = src.pdfBug === true;
  14625. const CanvasFactory = src.CanvasFactory || DefaultCanvasFactory;
  14626. const FilterFactory = src.FilterFactory || DefaultFilterFactory;
  14627. const enableHWA = src.enableHWA === true;
  14628. const length = rangeTransport ? rangeTransport.length : src.length ?? NaN;
  14629. const useSystemFonts = typeof src.useSystemFonts === "boolean" ? src.useSystemFonts : !isNodeJS && !disableFontFace;
  14630. const useWorkerFetch = typeof src.useWorkerFetch === "boolean" ? src.useWorkerFetch : CMapReaderFactory === DOMCMapReaderFactory && StandardFontDataFactory === DOMStandardFontDataFactory && cMapUrl && standardFontDataUrl && isValidFetchUrl(cMapUrl, document.baseURI) && isValidFetchUrl(standardFontDataUrl, document.baseURI);
  14631. if (src.canvasFactory) {
  14632. deprecated("`canvasFactory`-instance option, please use `CanvasFactory` instead.");
  14633. }
  14634. if (src.filterFactory) {
  14635. deprecated("`filterFactory`-instance option, please use `FilterFactory` instead.");
  14636. }
  14637. const styleElement = null;
  14638. setVerbosityLevel(verbosity);
  14639. const transportFactory = {
  14640. canvasFactory: new CanvasFactory({
  14641. ownerDocument,
  14642. enableHWA
  14643. }),
  14644. filterFactory: new FilterFactory({
  14645. docId,
  14646. ownerDocument
  14647. }),
  14648. cMapReaderFactory: useWorkerFetch ? null : new CMapReaderFactory({
  14649. baseUrl: cMapUrl,
  14650. isCompressed: cMapPacked
  14651. }),
  14652. standardFontDataFactory: useWorkerFetch ? null : new StandardFontDataFactory({
  14653. baseUrl: standardFontDataUrl
  14654. })
  14655. };
  14656. if (!worker) {
  14657. const workerParams = {
  14658. verbosity,
  14659. port: GlobalWorkerOptions.workerPort
  14660. };
  14661. worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams);
  14662. task._worker = worker;
  14663. }
  14664. const docParams = {
  14665. docId,
  14666. apiVersion: "4.7.76",
  14667. data,
  14668. password,
  14669. disableAutoFetch,
  14670. rangeChunkSize,
  14671. length,
  14672. docBaseUrl,
  14673. enableXfa,
  14674. evaluatorOptions: {
  14675. maxImageSize,
  14676. disableFontFace,
  14677. ignoreErrors,
  14678. isEvalSupported,
  14679. isOffscreenCanvasSupported,
  14680. canvasMaxAreaInBytes,
  14681. fontExtraProperties,
  14682. useSystemFonts,
  14683. cMapUrl: useWorkerFetch ? cMapUrl : null,
  14684. standardFontDataUrl: useWorkerFetch ? standardFontDataUrl : null
  14685. }
  14686. };
  14687. const transportParams = {
  14688. disableFontFace,
  14689. fontExtraProperties,
  14690. ownerDocument,
  14691. pdfBug,
  14692. styleElement,
  14693. loadingParams: {
  14694. disableAutoFetch,
  14695. enableXfa
  14696. }
  14697. };
  14698. worker.promise.then(function () {
  14699. if (task.destroyed) {
  14700. throw new Error("Loading aborted");
  14701. }
  14702. if (worker.destroyed) {
  14703. throw new Error("Worker was destroyed");
  14704. }
  14705. const workerIdPromise = worker.messageHandler.sendWithPromise("GetDocRequest", docParams, data ? [data.buffer] : null);
  14706. let networkStream;
  14707. if (rangeTransport) {
  14708. networkStream = new PDFDataTransportStream(rangeTransport, {
  14709. disableRange,
  14710. disableStream
  14711. });
  14712. } else if (!data) {
  14713. if (!url) {
  14714. throw new Error("getDocument - no `url` parameter provided.");
  14715. }
  14716. let NetworkStream;
  14717. if (isNodeJS) {
  14718. const isFetchSupported = typeof fetch !== "undefined" && typeof Response !== "undefined" && "body" in Response.prototype;
  14719. NetworkStream = isFetchSupported && isValidFetchUrl(url) ? PDFFetchStream : PDFNodeStream;
  14720. } else {
  14721. NetworkStream = isValidFetchUrl(url) ? PDFFetchStream : PDFNetworkStream;
  14722. }
  14723. networkStream = new NetworkStream({
  14724. url,
  14725. length,
  14726. httpHeaders,
  14727. withCredentials,
  14728. rangeChunkSize,
  14729. disableRange,
  14730. disableStream
  14731. });
  14732. }
  14733. return workerIdPromise.then(workerId => {
  14734. if (task.destroyed) {
  14735. throw new Error("Loading aborted");
  14736. }
  14737. if (worker.destroyed) {
  14738. throw new Error("Worker was destroyed");
  14739. }
  14740. const messageHandler = new MessageHandler(docId, workerId, worker.port);
  14741. const transport = new WorkerTransport(messageHandler, task, networkStream, transportParams, transportFactory);
  14742. task._transport = transport;
  14743. messageHandler.send("Ready", null);
  14744. });
  14745. }).catch(task._capability.reject);
  14746. return task;
  14747. }
  14748. function getUrlProp(val) {
  14749. if (val instanceof URL) {
  14750. return val.href;
  14751. }
  14752. try {
  14753. return new URL(val, window.location).href;
  14754. } catch {
  14755. if (isNodeJS && typeof val === "string") {
  14756. return val;
  14757. }
  14758. }
  14759. throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");
  14760. }
  14761. function getDataProp(val) {
  14762. if (isNodeJS && typeof Buffer !== "undefined" && val instanceof Buffer) {
  14763. throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");
  14764. }
  14765. if (val instanceof Uint8Array && val.byteLength === val.buffer.byteLength) {
  14766. return val;
  14767. }
  14768. if (typeof val === "string") {
  14769. return stringToBytes(val);
  14770. }
  14771. if (val instanceof ArrayBuffer || ArrayBuffer.isView(val) || typeof val === "object" && !isNaN(val?.length)) {
  14772. return new Uint8Array(val);
  14773. }
  14774. throw new Error("Invalid PDF binary data: either TypedArray, " + "string, or array-like object is expected in the data property.");
  14775. }
  14776. function isRefProxy(ref) {
  14777. return typeof ref === "object" && Number.isInteger(ref?.num) && ref.num >= 0 && Number.isInteger(ref?.gen) && ref.gen >= 0;
  14778. }
  14779. class PDFDocumentLoadingTask {
  14780. static #docId = 0;
  14781. constructor() {
  14782. this._capability = Promise.withResolvers();
  14783. this._transport = null;
  14784. this._worker = null;
  14785. this.docId = `d${PDFDocumentLoadingTask.#docId++}`;
  14786. this.destroyed = false;
  14787. this.onPassword = null;
  14788. this.onProgress = null;
  14789. }
  14790. get promise() {
  14791. return this._capability.promise;
  14792. }
  14793. async destroy() {
  14794. this.destroyed = true;
  14795. try {
  14796. if (this._worker?.port) {
  14797. this._worker._pendingDestroy = true;
  14798. }
  14799. await this._transport?.destroy();
  14800. } catch (ex) {
  14801. if (this._worker?.port) {
  14802. delete this._worker._pendingDestroy;
  14803. }
  14804. throw ex;
  14805. }
  14806. this._transport = null;
  14807. if (this._worker) {
  14808. this._worker.destroy();
  14809. this._worker = null;
  14810. }
  14811. }
  14812. }
  14813. class PDFDataRangeTransport {
  14814. constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
  14815. this.length = length;
  14816. this.initialData = initialData;
  14817. this.progressiveDone = progressiveDone;
  14818. this.contentDispositionFilename = contentDispositionFilename;
  14819. this._rangeListeners = [];
  14820. this._progressListeners = [];
  14821. this._progressiveReadListeners = [];
  14822. this._progressiveDoneListeners = [];
  14823. this._readyCapability = Promise.withResolvers();
  14824. }
  14825. addRangeListener(listener) {
  14826. this._rangeListeners.push(listener);
  14827. }
  14828. addProgressListener(listener) {
  14829. this._progressListeners.push(listener);
  14830. }
  14831. addProgressiveReadListener(listener) {
  14832. this._progressiveReadListeners.push(listener);
  14833. }
  14834. addProgressiveDoneListener(listener) {
  14835. this._progressiveDoneListeners.push(listener);
  14836. }
  14837. onDataRange(begin, chunk) {
  14838. for (const listener of this._rangeListeners) {
  14839. listener(begin, chunk);
  14840. }
  14841. }
  14842. onDataProgress(loaded, total) {
  14843. this._readyCapability.promise.then(() => {
  14844. for (const listener of this._progressListeners) {
  14845. listener(loaded, total);
  14846. }
  14847. });
  14848. }
  14849. onDataProgressiveRead(chunk) {
  14850. this._readyCapability.promise.then(() => {
  14851. for (const listener of this._progressiveReadListeners) {
  14852. listener(chunk);
  14853. }
  14854. });
  14855. }
  14856. onDataProgressiveDone() {
  14857. this._readyCapability.promise.then(() => {
  14858. for (const listener of this._progressiveDoneListeners) {
  14859. listener();
  14860. }
  14861. });
  14862. }
  14863. transportReady() {
  14864. this._readyCapability.resolve();
  14865. }
  14866. requestDataRange(begin, end) {
  14867. unreachable("Abstract method PDFDataRangeTransport.requestDataRange");
  14868. }
  14869. abort() {}
  14870. }
  14871. class PDFDocumentProxy {
  14872. constructor(pdfInfo, transport) {
  14873. this._pdfInfo = pdfInfo;
  14874. this._transport = transport;
  14875. }
  14876. get annotationStorage() {
  14877. return this._transport.annotationStorage;
  14878. }
  14879. get canvasFactory() {
  14880. return this._transport.canvasFactory;
  14881. }
  14882. get filterFactory() {
  14883. return this._transport.filterFactory;
  14884. }
  14885. get numPages() {
  14886. return this._pdfInfo.numPages;
  14887. }
  14888. get fingerprints() {
  14889. return this._pdfInfo.fingerprints;
  14890. }
  14891. get isPureXfa() {
  14892. return shadow(this, "isPureXfa", !!this._transport._htmlForXfa);
  14893. }
  14894. get allXfaHtml() {
  14895. return this._transport._htmlForXfa;
  14896. }
  14897. getPage(pageNumber) {
  14898. return this._transport.getPage(pageNumber);
  14899. }
  14900. getPageIndex(ref) {
  14901. return this._transport.getPageIndex(ref);
  14902. }
  14903. getDestinations() {
  14904. return this._transport.getDestinations();
  14905. }
  14906. getDestination(id) {
  14907. return this._transport.getDestination(id);
  14908. }
  14909. getPageLabels() {
  14910. return this._transport.getPageLabels();
  14911. }
  14912. getPageLayout() {
  14913. return this._transport.getPageLayout();
  14914. }
  14915. getPageMode() {
  14916. return this._transport.getPageMode();
  14917. }
  14918. getViewerPreferences() {
  14919. return this._transport.getViewerPreferences();
  14920. }
  14921. getOpenAction() {
  14922. return this._transport.getOpenAction();
  14923. }
  14924. getAttachments() {
  14925. return this._transport.getAttachments();
  14926. }
  14927. getJSActions() {
  14928. return this._transport.getDocJSActions();
  14929. }
  14930. getOutline() {
  14931. return this._transport.getOutline();
  14932. }
  14933. getOptionalContentConfig({
  14934. intent = "display"
  14935. } = {}) {
  14936. const {
  14937. renderingIntent
  14938. } = this._transport.getRenderingIntent(intent);
  14939. return this._transport.getOptionalContentConfig(renderingIntent);
  14940. }
  14941. getPermissions() {
  14942. return this._transport.getPermissions();
  14943. }
  14944. getMetadata() {
  14945. return this._transport.getMetadata();
  14946. }
  14947. getMarkInfo() {
  14948. return this._transport.getMarkInfo();
  14949. }
  14950. getData() {
  14951. return this._transport.getData();
  14952. }
  14953. saveDocument() {
  14954. return this._transport.saveDocument();
  14955. }
  14956. getDownloadInfo() {
  14957. return this._transport.downloadInfoCapability.promise;
  14958. }
  14959. cleanup(keepLoadedFonts = false) {
  14960. return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
  14961. }
  14962. destroy() {
  14963. return this.loadingTask.destroy();
  14964. }
  14965. cachedPageNumber(ref) {
  14966. return this._transport.cachedPageNumber(ref);
  14967. }
  14968. get loadingParams() {
  14969. return this._transport.loadingParams;
  14970. }
  14971. get loadingTask() {
  14972. return this._transport.loadingTask;
  14973. }
  14974. getFieldObjects() {
  14975. return this._transport.getFieldObjects();
  14976. }
  14977. hasJSActions() {
  14978. return this._transport.hasJSActions();
  14979. }
  14980. getCalculationOrderIds() {
  14981. return this._transport.getCalculationOrderIds();
  14982. }
  14983. }
  14984. class PDFPageProxy {
  14985. #delayedCleanupTimeout = null;
  14986. #pendingCleanup = false;
  14987. constructor(pageIndex, pageInfo, transport, pdfBug = false) {
  14988. this._pageIndex = pageIndex;
  14989. this._pageInfo = pageInfo;
  14990. this._transport = transport;
  14991. this._stats = pdfBug ? new StatTimer() : null;
  14992. this._pdfBug = pdfBug;
  14993. this.commonObjs = transport.commonObjs;
  14994. this.objs = new PDFObjects();
  14995. this._maybeCleanupAfterRender = false;
  14996. this._intentStates = new Map();
  14997. this.destroyed = false;
  14998. }
  14999. get pageNumber() {
  15000. return this._pageIndex + 1;
  15001. }
  15002. get rotate() {
  15003. return this._pageInfo.rotate;
  15004. }
  15005. get ref() {
  15006. return this._pageInfo.ref;
  15007. }
  15008. get userUnit() {
  15009. return this._pageInfo.userUnit;
  15010. }
  15011. get view() {
  15012. return this._pageInfo.view;
  15013. }
  15014. getViewport({
  15015. scale,
  15016. rotation = this.rotate,
  15017. offsetX = 0,
  15018. offsetY = 0,
  15019. dontFlip = false
  15020. } = {}) {
  15021. return new PageViewport({
  15022. viewBox: this.view,
  15023. scale,
  15024. rotation,
  15025. offsetX,
  15026. offsetY,
  15027. dontFlip
  15028. });
  15029. }
  15030. getAnnotations({
  15031. intent = "display"
  15032. } = {}) {
  15033. const {
  15034. renderingIntent
  15035. } = this._transport.getRenderingIntent(intent);
  15036. return this._transport.getAnnotations(this._pageIndex, renderingIntent);
  15037. }
  15038. getJSActions() {
  15039. return this._transport.getPageJSActions(this._pageIndex);
  15040. }
  15041. get filterFactory() {
  15042. return this._transport.filterFactory;
  15043. }
  15044. get isPureXfa() {
  15045. return shadow(this, "isPureXfa", !!this._transport._htmlForXfa);
  15046. }
  15047. async getXfa() {
  15048. return this._transport._htmlForXfa?.children[this._pageIndex] || null;
  15049. }
  15050. render({
  15051. canvasContext,
  15052. viewport,
  15053. intent = "display",
  15054. annotationMode = AnnotationMode.ENABLE,
  15055. transform = null,
  15056. background = null,
  15057. optionalContentConfigPromise = null,
  15058. annotationCanvasMap = null,
  15059. pageColors = null,
  15060. printAnnotationStorage = null,
  15061. isEditing = false
  15062. }) {
  15063. this._stats?.time("Overall");
  15064. const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing);
  15065. const {
  15066. renderingIntent,
  15067. cacheKey
  15068. } = intentArgs;
  15069. this.#pendingCleanup = false;
  15070. this.#abortDelayedCleanup();
  15071. optionalContentConfigPromise ||= this._transport.getOptionalContentConfig(renderingIntent);
  15072. let intentState = this._intentStates.get(cacheKey);
  15073. if (!intentState) {
  15074. intentState = Object.create(null);
  15075. this._intentStates.set(cacheKey, intentState);
  15076. }
  15077. if (intentState.streamReaderCancelTimeout) {
  15078. clearTimeout(intentState.streamReaderCancelTimeout);
  15079. intentState.streamReaderCancelTimeout = null;
  15080. }
  15081. const intentPrint = !!(renderingIntent & RenderingIntentFlag.PRINT);
  15082. if (!intentState.displayReadyCapability) {
  15083. intentState.displayReadyCapability = Promise.withResolvers();
  15084. intentState.operatorList = {
  15085. fnArray: [],
  15086. argsArray: [],
  15087. lastChunk: false,
  15088. separateAnnots: null
  15089. };
  15090. this._stats?.time("Page Request");
  15091. this._pumpOperatorList(intentArgs);
  15092. }
  15093. const complete = error => {
  15094. intentState.renderTasks.delete(internalRenderTask);
  15095. if (this._maybeCleanupAfterRender || intentPrint) {
  15096. this.#pendingCleanup = true;
  15097. }
  15098. this.#tryCleanup(!intentPrint);
  15099. if (error) {
  15100. internalRenderTask.capability.reject(error);
  15101. this._abortOperatorList({
  15102. intentState,
  15103. reason: error instanceof Error ? error : new Error(error)
  15104. });
  15105. } else {
  15106. internalRenderTask.capability.resolve();
  15107. }
  15108. if (this._stats) {
  15109. this._stats.timeEnd("Rendering");
  15110. this._stats.timeEnd("Overall");
  15111. if (globalThis.Stats?.enabled) {
  15112. globalThis.Stats.add(this.pageNumber, this._stats);
  15113. }
  15114. }
  15115. };
  15116. const internalRenderTask = new InternalRenderTask({
  15117. callback: complete,
  15118. params: {
  15119. canvasContext,
  15120. viewport,
  15121. transform,
  15122. background
  15123. },
  15124. objs: this.objs,
  15125. commonObjs: this.commonObjs,
  15126. annotationCanvasMap,
  15127. operatorList: intentState.operatorList,
  15128. pageIndex: this._pageIndex,
  15129. canvasFactory: this._transport.canvasFactory,
  15130. filterFactory: this._transport.filterFactory,
  15131. useRequestAnimationFrame: !intentPrint,
  15132. pdfBug: this._pdfBug,
  15133. pageColors
  15134. });
  15135. (intentState.renderTasks ||= new Set()).add(internalRenderTask);
  15136. const renderTask = internalRenderTask.task;
  15137. Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
  15138. if (this.destroyed) {
  15139. complete();
  15140. return;
  15141. }
  15142. this._stats?.time("Rendering");
  15143. if (!(optionalContentConfig.renderingIntent & renderingIntent)) {
  15144. throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` " + "and `PDFDocumentProxy.getOptionalContentConfig` methods.");
  15145. }
  15146. internalRenderTask.initializeGraphics({
  15147. transparency,
  15148. optionalContentConfig
  15149. });
  15150. internalRenderTask.operatorListChanged();
  15151. }).catch(complete);
  15152. return renderTask;
  15153. }
  15154. getOperatorList({
  15155. intent = "display",
  15156. annotationMode = AnnotationMode.ENABLE,
  15157. printAnnotationStorage = null,
  15158. isEditing = false
  15159. } = {}) {
  15160. function operatorListChanged() {
  15161. if (intentState.operatorList.lastChunk) {
  15162. intentState.opListReadCapability.resolve(intentState.operatorList);
  15163. intentState.renderTasks.delete(opListTask);
  15164. }
  15165. }
  15166. const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing, true);
  15167. let intentState = this._intentStates.get(intentArgs.cacheKey);
  15168. if (!intentState) {
  15169. intentState = Object.create(null);
  15170. this._intentStates.set(intentArgs.cacheKey, intentState);
  15171. }
  15172. let opListTask;
  15173. if (!intentState.opListReadCapability) {
  15174. opListTask = Object.create(null);
  15175. opListTask.operatorListChanged = operatorListChanged;
  15176. intentState.opListReadCapability = Promise.withResolvers();
  15177. (intentState.renderTasks ||= new Set()).add(opListTask);
  15178. intentState.operatorList = {
  15179. fnArray: [],
  15180. argsArray: [],
  15181. lastChunk: false,
  15182. separateAnnots: null
  15183. };
  15184. this._stats?.time("Page Request");
  15185. this._pumpOperatorList(intentArgs);
  15186. }
  15187. return intentState.opListReadCapability.promise;
  15188. }
  15189. streamTextContent({
  15190. includeMarkedContent = false,
  15191. disableNormalization = false
  15192. } = {}) {
  15193. const TEXT_CONTENT_CHUNK_SIZE = 100;
  15194. return this._transport.messageHandler.sendWithStream("GetTextContent", {
  15195. pageIndex: this._pageIndex,
  15196. includeMarkedContent: includeMarkedContent === true,
  15197. disableNormalization: disableNormalization === true
  15198. }, {
  15199. highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
  15200. size(textContent) {
  15201. return textContent.items.length;
  15202. }
  15203. });
  15204. }
  15205. getTextContent(params = {}) {
  15206. if (this._transport._htmlForXfa) {
  15207. return this.getXfa().then(xfa => XfaText.textContent(xfa));
  15208. }
  15209. const readableStream = this.streamTextContent(params);
  15210. return new Promise(function (resolve, reject) {
  15211. function pump() {
  15212. reader.read().then(function ({
  15213. value,
  15214. done
  15215. }) {
  15216. if (done) {
  15217. resolve(textContent);
  15218. return;
  15219. }
  15220. textContent.lang ??= value.lang;
  15221. Object.assign(textContent.styles, value.styles);
  15222. textContent.items.push(...value.items);
  15223. pump();
  15224. }, reject);
  15225. }
  15226. const reader = readableStream.getReader();
  15227. const textContent = {
  15228. items: [],
  15229. styles: Object.create(null),
  15230. lang: null
  15231. };
  15232. pump();
  15233. });
  15234. }
  15235. getStructTree() {
  15236. return this._transport.getStructTree(this._pageIndex);
  15237. }
  15238. _destroy() {
  15239. this.destroyed = true;
  15240. const waitOn = [];
  15241. for (const intentState of this._intentStates.values()) {
  15242. this._abortOperatorList({
  15243. intentState,
  15244. reason: new Error("Page was destroyed."),
  15245. force: true
  15246. });
  15247. if (intentState.opListReadCapability) {
  15248. continue;
  15249. }
  15250. for (const internalRenderTask of intentState.renderTasks) {
  15251. waitOn.push(internalRenderTask.completed);
  15252. internalRenderTask.cancel();
  15253. }
  15254. }
  15255. this.objs.clear();
  15256. this.#pendingCleanup = false;
  15257. this.#abortDelayedCleanup();
  15258. return Promise.all(waitOn);
  15259. }
  15260. cleanup(resetStats = false) {
  15261. this.#pendingCleanup = true;
  15262. const success = this.#tryCleanup(false);
  15263. if (resetStats && success) {
  15264. this._stats &&= new StatTimer();
  15265. }
  15266. return success;
  15267. }
  15268. #tryCleanup(delayed = false) {
  15269. this.#abortDelayedCleanup();
  15270. if (!this.#pendingCleanup || this.destroyed) {
  15271. return false;
  15272. }
  15273. if (delayed) {
  15274. this.#delayedCleanupTimeout = setTimeout(() => {
  15275. this.#delayedCleanupTimeout = null;
  15276. this.#tryCleanup(false);
  15277. }, DELAYED_CLEANUP_TIMEOUT);
  15278. return false;
  15279. }
  15280. for (const {
  15281. renderTasks,
  15282. operatorList
  15283. } of this._intentStates.values()) {
  15284. if (renderTasks.size > 0 || !operatorList.lastChunk) {
  15285. return false;
  15286. }
  15287. }
  15288. this._intentStates.clear();
  15289. this.objs.clear();
  15290. this.#pendingCleanup = false;
  15291. return true;
  15292. }
  15293. #abortDelayedCleanup() {
  15294. if (this.#delayedCleanupTimeout) {
  15295. clearTimeout(this.#delayedCleanupTimeout);
  15296. this.#delayedCleanupTimeout = null;
  15297. }
  15298. }
  15299. _startRenderPage(transparency, cacheKey) {
  15300. const intentState = this._intentStates.get(cacheKey);
  15301. if (!intentState) {
  15302. return;
  15303. }
  15304. this._stats?.timeEnd("Page Request");
  15305. intentState.displayReadyCapability?.resolve(transparency);
  15306. }
  15307. _renderPageChunk(operatorListChunk, intentState) {
  15308. for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
  15309. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  15310. intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
  15311. }
  15312. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  15313. intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots;
  15314. for (const internalRenderTask of intentState.renderTasks) {
  15315. internalRenderTask.operatorListChanged();
  15316. }
  15317. if (operatorListChunk.lastChunk) {
  15318. this.#tryCleanup(true);
  15319. }
  15320. }
  15321. _pumpOperatorList({
  15322. renderingIntent,
  15323. cacheKey,
  15324. annotationStorageSerializable,
  15325. modifiedIds
  15326. }) {
  15327. const {
  15328. map,
  15329. transfer
  15330. } = annotationStorageSerializable;
  15331. const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", {
  15332. pageIndex: this._pageIndex,
  15333. intent: renderingIntent,
  15334. cacheKey,
  15335. annotationStorage: map,
  15336. modifiedIds
  15337. }, transfer);
  15338. const reader = readableStream.getReader();
  15339. const intentState = this._intentStates.get(cacheKey);
  15340. intentState.streamReader = reader;
  15341. const pump = () => {
  15342. reader.read().then(({
  15343. value,
  15344. done
  15345. }) => {
  15346. if (done) {
  15347. intentState.streamReader = null;
  15348. return;
  15349. }
  15350. if (this._transport.destroyed) {
  15351. return;
  15352. }
  15353. this._renderPageChunk(value, intentState);
  15354. pump();
  15355. }, reason => {
  15356. intentState.streamReader = null;
  15357. if (this._transport.destroyed) {
  15358. return;
  15359. }
  15360. if (intentState.operatorList) {
  15361. intentState.operatorList.lastChunk = true;
  15362. for (const internalRenderTask of intentState.renderTasks) {
  15363. internalRenderTask.operatorListChanged();
  15364. }
  15365. this.#tryCleanup(true);
  15366. }
  15367. if (intentState.displayReadyCapability) {
  15368. intentState.displayReadyCapability.reject(reason);
  15369. } else if (intentState.opListReadCapability) {
  15370. intentState.opListReadCapability.reject(reason);
  15371. } else {
  15372. throw reason;
  15373. }
  15374. });
  15375. };
  15376. pump();
  15377. }
  15378. _abortOperatorList({
  15379. intentState,
  15380. reason,
  15381. force = false
  15382. }) {
  15383. if (!intentState.streamReader) {
  15384. return;
  15385. }
  15386. if (intentState.streamReaderCancelTimeout) {
  15387. clearTimeout(intentState.streamReaderCancelTimeout);
  15388. intentState.streamReaderCancelTimeout = null;
  15389. }
  15390. if (!force) {
  15391. if (intentState.renderTasks.size > 0) {
  15392. return;
  15393. }
  15394. if (reason instanceof RenderingCancelledException) {
  15395. let delay = RENDERING_CANCELLED_TIMEOUT;
  15396. if (reason.extraDelay > 0 && reason.extraDelay < 1000) {
  15397. delay += reason.extraDelay;
  15398. }
  15399. intentState.streamReaderCancelTimeout = setTimeout(() => {
  15400. intentState.streamReaderCancelTimeout = null;
  15401. this._abortOperatorList({
  15402. intentState,
  15403. reason,
  15404. force: true
  15405. });
  15406. }, delay);
  15407. return;
  15408. }
  15409. }
  15410. intentState.streamReader.cancel(new AbortException(reason.message)).catch(() => {});
  15411. intentState.streamReader = null;
  15412. if (this._transport.destroyed) {
  15413. return;
  15414. }
  15415. for (const [curCacheKey, curIntentState] of this._intentStates) {
  15416. if (curIntentState === intentState) {
  15417. this._intentStates.delete(curCacheKey);
  15418. break;
  15419. }
  15420. }
  15421. this.cleanup();
  15422. }
  15423. get stats() {
  15424. return this._stats;
  15425. }
  15426. }
  15427. class LoopbackPort {
  15428. #listeners = new Set();
  15429. #deferred = Promise.resolve();
  15430. postMessage(obj, transfer) {
  15431. const event = {
  15432. data: structuredClone(obj, transfer ? {
  15433. transfer
  15434. } : null)
  15435. };
  15436. this.#deferred.then(() => {
  15437. for (const listener of this.#listeners) {
  15438. listener.call(this, event);
  15439. }
  15440. });
  15441. }
  15442. addEventListener(name, listener) {
  15443. this.#listeners.add(listener);
  15444. }
  15445. removeEventListener(name, listener) {
  15446. this.#listeners.delete(listener);
  15447. }
  15448. terminate() {
  15449. this.#listeners.clear();
  15450. }
  15451. }
  15452. class PDFWorker {
  15453. static #fakeWorkerId = 0;
  15454. static #isWorkerDisabled = false;
  15455. static #workerPorts;
  15456. static {
  15457. if (isNodeJS) {
  15458. this.#isWorkerDisabled = true;
  15459. GlobalWorkerOptions.workerSrc ||= "./pdf.worker.mjs";
  15460. }
  15461. this._isSameOrigin = (baseUrl, otherUrl) => {
  15462. let base;
  15463. try {
  15464. base = new URL(baseUrl);
  15465. if (!base.origin || base.origin === "null") {
  15466. return false;
  15467. }
  15468. } catch {
  15469. return false;
  15470. }
  15471. const other = new URL(otherUrl, base);
  15472. return base.origin === other.origin;
  15473. };
  15474. this._createCDNWrapper = url => {
  15475. const wrapper = `await import("${url}");`;
  15476. return URL.createObjectURL(new Blob([wrapper], {
  15477. type: "text/javascript"
  15478. }));
  15479. };
  15480. }
  15481. constructor({
  15482. name = null,
  15483. port = null,
  15484. verbosity = getVerbosityLevel()
  15485. } = {}) {
  15486. this.name = name;
  15487. this.destroyed = false;
  15488. this.verbosity = verbosity;
  15489. this._readyCapability = Promise.withResolvers();
  15490. this._port = null;
  15491. this._webWorker = null;
  15492. this._messageHandler = null;
  15493. if (port) {
  15494. if (PDFWorker.#workerPorts?.has(port)) {
  15495. throw new Error("Cannot use more than one PDFWorker per port.");
  15496. }
  15497. (PDFWorker.#workerPorts ||= new WeakMap()).set(port, this);
  15498. this._initializeFromPort(port);
  15499. return;
  15500. }
  15501. this._initialize();
  15502. }
  15503. get promise() {
  15504. if (isNodeJS) {
  15505. return Promise.all([NodePackages.promise, this._readyCapability.promise]);
  15506. }
  15507. return this._readyCapability.promise;
  15508. }
  15509. #resolve() {
  15510. this._readyCapability.resolve();
  15511. this._messageHandler.send("configure", {
  15512. verbosity: this.verbosity
  15513. });
  15514. }
  15515. get port() {
  15516. return this._port;
  15517. }
  15518. get messageHandler() {
  15519. return this._messageHandler;
  15520. }
  15521. _initializeFromPort(port) {
  15522. this._port = port;
  15523. this._messageHandler = new MessageHandler("main", "worker", port);
  15524. this._messageHandler.on("ready", function () {});
  15525. this.#resolve();
  15526. }
  15527. _initialize() {
  15528. if (PDFWorker.#isWorkerDisabled || PDFWorker.#mainThreadWorkerMessageHandler) {
  15529. this._setupFakeWorker();
  15530. return;
  15531. }
  15532. let {
  15533. workerSrc
  15534. } = PDFWorker;
  15535. try {
  15536. if (!PDFWorker._isSameOrigin(window.location.href, workerSrc)) {
  15537. workerSrc = PDFWorker._createCDNWrapper(new URL(workerSrc, window.location).href);
  15538. }
  15539. const worker = new Worker(workerSrc, {
  15540. type: "module"
  15541. });
  15542. const messageHandler = new MessageHandler("main", "worker", worker);
  15543. const terminateEarly = () => {
  15544. ac.abort();
  15545. messageHandler.destroy();
  15546. worker.terminate();
  15547. if (this.destroyed) {
  15548. this._readyCapability.reject(new Error("Worker was destroyed"));
  15549. } else {
  15550. this._setupFakeWorker();
  15551. }
  15552. };
  15553. const ac = new AbortController();
  15554. worker.addEventListener("error", () => {
  15555. if (!this._webWorker) {
  15556. terminateEarly();
  15557. }
  15558. }, {
  15559. signal: ac.signal
  15560. });
  15561. messageHandler.on("test", data => {
  15562. ac.abort();
  15563. if (this.destroyed || !data) {
  15564. terminateEarly();
  15565. return;
  15566. }
  15567. this._messageHandler = messageHandler;
  15568. this._port = worker;
  15569. this._webWorker = worker;
  15570. this.#resolve();
  15571. });
  15572. messageHandler.on("ready", data => {
  15573. ac.abort();
  15574. if (this.destroyed) {
  15575. terminateEarly();
  15576. return;
  15577. }
  15578. try {
  15579. sendTest();
  15580. } catch {
  15581. this._setupFakeWorker();
  15582. }
  15583. });
  15584. const sendTest = () => {
  15585. const testObj = new Uint8Array();
  15586. messageHandler.send("test", testObj, [testObj.buffer]);
  15587. };
  15588. sendTest();
  15589. return;
  15590. } catch {
  15591. info("The worker has been disabled.");
  15592. }
  15593. this._setupFakeWorker();
  15594. }
  15595. _setupFakeWorker() {
  15596. if (!PDFWorker.#isWorkerDisabled) {
  15597. warn("Setting up fake worker.");
  15598. PDFWorker.#isWorkerDisabled = true;
  15599. }
  15600. PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => {
  15601. if (this.destroyed) {
  15602. this._readyCapability.reject(new Error("Worker was destroyed"));
  15603. return;
  15604. }
  15605. const port = new LoopbackPort();
  15606. this._port = port;
  15607. const id = `fake${PDFWorker.#fakeWorkerId++}`;
  15608. const workerHandler = new MessageHandler(id + "_worker", id, port);
  15609. WorkerMessageHandler.setup(workerHandler, port);
  15610. this._messageHandler = new MessageHandler(id, id + "_worker", port);
  15611. this.#resolve();
  15612. }).catch(reason => {
  15613. this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
  15614. });
  15615. }
  15616. destroy() {
  15617. this.destroyed = true;
  15618. if (this._webWorker) {
  15619. this._webWorker.terminate();
  15620. this._webWorker = null;
  15621. }
  15622. PDFWorker.#workerPorts?.delete(this._port);
  15623. this._port = null;
  15624. if (this._messageHandler) {
  15625. this._messageHandler.destroy();
  15626. this._messageHandler = null;
  15627. }
  15628. }
  15629. static fromPort(params) {
  15630. if (!params?.port) {
  15631. throw new Error("PDFWorker.fromPort - invalid method signature.");
  15632. }
  15633. const cachedPort = this.#workerPorts?.get(params.port);
  15634. if (cachedPort) {
  15635. if (cachedPort._pendingDestroy) {
  15636. throw new Error("PDFWorker.fromPort - the worker is being destroyed.\n" + "Please remember to await `PDFDocumentLoadingTask.destroy()`-calls.");
  15637. }
  15638. return cachedPort;
  15639. }
  15640. return new PDFWorker(params);
  15641. }
  15642. static get workerSrc() {
  15643. if (GlobalWorkerOptions.workerSrc) {
  15644. return GlobalWorkerOptions.workerSrc;
  15645. }
  15646. throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
  15647. }
  15648. static get #mainThreadWorkerMessageHandler() {
  15649. try {
  15650. return globalThis.pdfjsWorker?.WorkerMessageHandler || null;
  15651. } catch {
  15652. return null;
  15653. }
  15654. }
  15655. static get _setupFakeWorkerGlobal() {
  15656. const loader = async () => {
  15657. if (this.#mainThreadWorkerMessageHandler) {
  15658. return this.#mainThreadWorkerMessageHandler;
  15659. }
  15660. const worker = await import(/*webpackIgnore: true*/this.workerSrc);
  15661. return worker.WorkerMessageHandler;
  15662. };
  15663. return shadow(this, "_setupFakeWorkerGlobal", loader());
  15664. }
  15665. }
  15666. class WorkerTransport {
  15667. #methodPromises = new Map();
  15668. #pageCache = new Map();
  15669. #pagePromises = new Map();
  15670. #pageRefCache = new Map();
  15671. #passwordCapability = null;
  15672. constructor(messageHandler, loadingTask, networkStream, params, factory) {
  15673. this.messageHandler = messageHandler;
  15674. this.loadingTask = loadingTask;
  15675. this.commonObjs = new PDFObjects();
  15676. this.fontLoader = new FontLoader({
  15677. ownerDocument: params.ownerDocument,
  15678. styleElement: params.styleElement
  15679. });
  15680. this.loadingParams = params.loadingParams;
  15681. this._params = params;
  15682. this.canvasFactory = factory.canvasFactory;
  15683. this.filterFactory = factory.filterFactory;
  15684. this.cMapReaderFactory = factory.cMapReaderFactory;
  15685. this.standardFontDataFactory = factory.standardFontDataFactory;
  15686. this.destroyed = false;
  15687. this.destroyCapability = null;
  15688. this._networkStream = networkStream;
  15689. this._fullReader = null;
  15690. this._lastProgress = null;
  15691. this.downloadInfoCapability = Promise.withResolvers();
  15692. this.setupMessageHandler();
  15693. }
  15694. #cacheSimpleMethod(name, data = null) {
  15695. const cachedPromise = this.#methodPromises.get(name);
  15696. if (cachedPromise) {
  15697. return cachedPromise;
  15698. }
  15699. const promise = this.messageHandler.sendWithPromise(name, data);
  15700. this.#methodPromises.set(name, promise);
  15701. return promise;
  15702. }
  15703. get annotationStorage() {
  15704. return shadow(this, "annotationStorage", new AnnotationStorage());
  15705. }
  15706. getRenderingIntent(intent, annotationMode = AnnotationMode.ENABLE, printAnnotationStorage = null, isEditing = false, isOpList = false) {
  15707. let renderingIntent = RenderingIntentFlag.DISPLAY;
  15708. let annotationStorageSerializable = SerializableEmpty;
  15709. switch (intent) {
  15710. case "any":
  15711. renderingIntent = RenderingIntentFlag.ANY;
  15712. break;
  15713. case "display":
  15714. break;
  15715. case "print":
  15716. renderingIntent = RenderingIntentFlag.PRINT;
  15717. break;
  15718. default:
  15719. warn(`getRenderingIntent - invalid intent: ${intent}`);
  15720. }
  15721. const annotationStorage = renderingIntent & RenderingIntentFlag.PRINT && printAnnotationStorage instanceof PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage;
  15722. switch (annotationMode) {
  15723. case AnnotationMode.DISABLE:
  15724. renderingIntent += RenderingIntentFlag.ANNOTATIONS_DISABLE;
  15725. break;
  15726. case AnnotationMode.ENABLE:
  15727. break;
  15728. case AnnotationMode.ENABLE_FORMS:
  15729. renderingIntent += RenderingIntentFlag.ANNOTATIONS_FORMS;
  15730. break;
  15731. case AnnotationMode.ENABLE_STORAGE:
  15732. renderingIntent += RenderingIntentFlag.ANNOTATIONS_STORAGE;
  15733. annotationStorageSerializable = annotationStorage.serializable;
  15734. break;
  15735. default:
  15736. warn(`getRenderingIntent - invalid annotationMode: ${annotationMode}`);
  15737. }
  15738. if (isEditing) {
  15739. renderingIntent += RenderingIntentFlag.IS_EDITING;
  15740. }
  15741. if (isOpList) {
  15742. renderingIntent += RenderingIntentFlag.OPLIST;
  15743. }
  15744. const {
  15745. ids: modifiedIds,
  15746. hash: modifiedIdsHash
  15747. } = annotationStorage.modifiedIds;
  15748. const cacheKeyBuf = [renderingIntent, annotationStorageSerializable.hash, modifiedIdsHash];
  15749. return {
  15750. renderingIntent,
  15751. cacheKey: cacheKeyBuf.join("_"),
  15752. annotationStorageSerializable,
  15753. modifiedIds
  15754. };
  15755. }
  15756. destroy() {
  15757. if (this.destroyCapability) {
  15758. return this.destroyCapability.promise;
  15759. }
  15760. this.destroyed = true;
  15761. this.destroyCapability = Promise.withResolvers();
  15762. this.#passwordCapability?.reject(new Error("Worker was destroyed during onPassword callback"));
  15763. const waitOn = [];
  15764. for (const page of this.#pageCache.values()) {
  15765. waitOn.push(page._destroy());
  15766. }
  15767. this.#pageCache.clear();
  15768. this.#pagePromises.clear();
  15769. this.#pageRefCache.clear();
  15770. if (this.hasOwnProperty("annotationStorage")) {
  15771. this.annotationStorage.resetModified();
  15772. }
  15773. const terminated = this.messageHandler.sendWithPromise("Terminate", null);
  15774. waitOn.push(terminated);
  15775. Promise.all(waitOn).then(() => {
  15776. this.commonObjs.clear();
  15777. this.fontLoader.clear();
  15778. this.#methodPromises.clear();
  15779. this.filterFactory.destroy();
  15780. TextLayer.cleanup();
  15781. this._networkStream?.cancelAllRequests(new AbortException("Worker was terminated."));
  15782. if (this.messageHandler) {
  15783. this.messageHandler.destroy();
  15784. this.messageHandler = null;
  15785. }
  15786. this.destroyCapability.resolve();
  15787. }, this.destroyCapability.reject);
  15788. return this.destroyCapability.promise;
  15789. }
  15790. setupMessageHandler() {
  15791. const {
  15792. messageHandler,
  15793. loadingTask
  15794. } = this;
  15795. messageHandler.on("GetReader", (data, sink) => {
  15796. assert(this._networkStream, "GetReader - no `IPDFStream` instance available.");
  15797. this._fullReader = this._networkStream.getFullReader();
  15798. this._fullReader.onProgress = evt => {
  15799. this._lastProgress = {
  15800. loaded: evt.loaded,
  15801. total: evt.total
  15802. };
  15803. };
  15804. sink.onPull = () => {
  15805. this._fullReader.read().then(function ({
  15806. value,
  15807. done
  15808. }) {
  15809. if (done) {
  15810. sink.close();
  15811. return;
  15812. }
  15813. assert(value instanceof ArrayBuffer, "GetReader - expected an ArrayBuffer.");
  15814. sink.enqueue(new Uint8Array(value), 1, [value]);
  15815. }).catch(reason => {
  15816. sink.error(reason);
  15817. });
  15818. };
  15819. sink.onCancel = reason => {
  15820. this._fullReader.cancel(reason);
  15821. sink.ready.catch(readyReason => {
  15822. if (this.destroyed) {
  15823. return;
  15824. }
  15825. throw readyReason;
  15826. });
  15827. };
  15828. });
  15829. messageHandler.on("ReaderHeadersReady", data => {
  15830. const headersCapability = Promise.withResolvers();
  15831. const fullReader = this._fullReader;
  15832. fullReader.headersReady.then(() => {
  15833. if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) {
  15834. if (this._lastProgress) {
  15835. loadingTask.onProgress?.(this._lastProgress);
  15836. }
  15837. fullReader.onProgress = evt => {
  15838. loadingTask.onProgress?.({
  15839. loaded: evt.loaded,
  15840. total: evt.total
  15841. });
  15842. };
  15843. }
  15844. headersCapability.resolve({
  15845. isStreamingSupported: fullReader.isStreamingSupported,
  15846. isRangeSupported: fullReader.isRangeSupported,
  15847. contentLength: fullReader.contentLength
  15848. });
  15849. }, headersCapability.reject);
  15850. return headersCapability.promise;
  15851. });
  15852. messageHandler.on("GetRangeReader", (data, sink) => {
  15853. assert(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
  15854. const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
  15855. if (!rangeReader) {
  15856. sink.close();
  15857. return;
  15858. }
  15859. sink.onPull = () => {
  15860. rangeReader.read().then(function ({
  15861. value,
  15862. done
  15863. }) {
  15864. if (done) {
  15865. sink.close();
  15866. return;
  15867. }
  15868. assert(value instanceof ArrayBuffer, "GetRangeReader - expected an ArrayBuffer.");
  15869. sink.enqueue(new Uint8Array(value), 1, [value]);
  15870. }).catch(reason => {
  15871. sink.error(reason);
  15872. });
  15873. };
  15874. sink.onCancel = reason => {
  15875. rangeReader.cancel(reason);
  15876. sink.ready.catch(readyReason => {
  15877. if (this.destroyed) {
  15878. return;
  15879. }
  15880. throw readyReason;
  15881. });
  15882. };
  15883. });
  15884. messageHandler.on("GetDoc", ({
  15885. pdfInfo
  15886. }) => {
  15887. this._numPages = pdfInfo.numPages;
  15888. this._htmlForXfa = pdfInfo.htmlForXfa;
  15889. delete pdfInfo.htmlForXfa;
  15890. loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
  15891. });
  15892. messageHandler.on("DocException", function (ex) {
  15893. let reason;
  15894. switch (ex.name) {
  15895. case "PasswordException":
  15896. reason = new PasswordException(ex.message, ex.code);
  15897. break;
  15898. case "InvalidPDFException":
  15899. reason = new InvalidPDFException(ex.message);
  15900. break;
  15901. case "MissingPDFException":
  15902. reason = new MissingPDFException(ex.message);
  15903. break;
  15904. case "UnexpectedResponseException":
  15905. reason = new UnexpectedResponseException(ex.message, ex.status);
  15906. break;
  15907. case "UnknownErrorException":
  15908. reason = new UnknownErrorException(ex.message, ex.details);
  15909. break;
  15910. default:
  15911. unreachable("DocException - expected a valid Error.");
  15912. }
  15913. loadingTask._capability.reject(reason);
  15914. });
  15915. messageHandler.on("PasswordRequest", exception => {
  15916. this.#passwordCapability = Promise.withResolvers();
  15917. if (loadingTask.onPassword) {
  15918. const updatePassword = password => {
  15919. if (password instanceof Error) {
  15920. this.#passwordCapability.reject(password);
  15921. } else {
  15922. this.#passwordCapability.resolve({
  15923. password
  15924. });
  15925. }
  15926. };
  15927. try {
  15928. loadingTask.onPassword(updatePassword, exception.code);
  15929. } catch (ex) {
  15930. this.#passwordCapability.reject(ex);
  15931. }
  15932. } else {
  15933. this.#passwordCapability.reject(new PasswordException(exception.message, exception.code));
  15934. }
  15935. return this.#passwordCapability.promise;
  15936. });
  15937. messageHandler.on("DataLoaded", data => {
  15938. loadingTask.onProgress?.({
  15939. loaded: data.length,
  15940. total: data.length
  15941. });
  15942. this.downloadInfoCapability.resolve(data);
  15943. });
  15944. messageHandler.on("StartRenderPage", data => {
  15945. if (this.destroyed) {
  15946. return;
  15947. }
  15948. const page = this.#pageCache.get(data.pageIndex);
  15949. page._startRenderPage(data.transparency, data.cacheKey);
  15950. });
  15951. messageHandler.on("commonobj", ([id, type, exportedData]) => {
  15952. if (this.destroyed) {
  15953. return null;
  15954. }
  15955. if (this.commonObjs.has(id)) {
  15956. return null;
  15957. }
  15958. switch (type) {
  15959. case "Font":
  15960. const {
  15961. disableFontFace,
  15962. fontExtraProperties,
  15963. pdfBug
  15964. } = this._params;
  15965. if ("error" in exportedData) {
  15966. const exportedError = exportedData.error;
  15967. warn(`Error during font loading: ${exportedError}`);
  15968. this.commonObjs.resolve(id, exportedError);
  15969. break;
  15970. }
  15971. const inspectFont = pdfBug && globalThis.FontInspector?.enabled ? (font, url) => globalThis.FontInspector.fontAdded(font, url) : null;
  15972. const font = new FontFaceObject(exportedData, {
  15973. disableFontFace,
  15974. inspectFont
  15975. });
  15976. this.fontLoader.bind(font).catch(() => messageHandler.sendWithPromise("FontFallback", {
  15977. id
  15978. })).finally(() => {
  15979. if (!fontExtraProperties && font.data) {
  15980. font.data = null;
  15981. }
  15982. this.commonObjs.resolve(id, font);
  15983. });
  15984. break;
  15985. case "CopyLocalImage":
  15986. const {
  15987. imageRef
  15988. } = exportedData;
  15989. assert(imageRef, "The imageRef must be defined.");
  15990. for (const pageProxy of this.#pageCache.values()) {
  15991. for (const [, data] of pageProxy.objs) {
  15992. if (data?.ref !== imageRef) {
  15993. continue;
  15994. }
  15995. if (!data.dataLen) {
  15996. return null;
  15997. }
  15998. this.commonObjs.resolve(id, structuredClone(data));
  15999. return data.dataLen;
  16000. }
  16001. }
  16002. break;
  16003. case "FontPath":
  16004. case "Image":
  16005. case "Pattern":
  16006. this.commonObjs.resolve(id, exportedData);
  16007. break;
  16008. default:
  16009. throw new Error(`Got unknown common object type ${type}`);
  16010. }
  16011. return null;
  16012. });
  16013. messageHandler.on("obj", ([id, pageIndex, type, imageData]) => {
  16014. if (this.destroyed) {
  16015. return;
  16016. }
  16017. const pageProxy = this.#pageCache.get(pageIndex);
  16018. if (pageProxy.objs.has(id)) {
  16019. return;
  16020. }
  16021. if (pageProxy._intentStates.size === 0) {
  16022. imageData?.bitmap?.close();
  16023. return;
  16024. }
  16025. switch (type) {
  16026. case "Image":
  16027. pageProxy.objs.resolve(id, imageData);
  16028. if (imageData?.dataLen > MAX_IMAGE_SIZE_TO_CACHE) {
  16029. pageProxy._maybeCleanupAfterRender = true;
  16030. }
  16031. break;
  16032. case "Pattern":
  16033. pageProxy.objs.resolve(id, imageData);
  16034. break;
  16035. default:
  16036. throw new Error(`Got unknown object type ${type}`);
  16037. }
  16038. });
  16039. messageHandler.on("DocProgress", data => {
  16040. if (this.destroyed) {
  16041. return;
  16042. }
  16043. loadingTask.onProgress?.({
  16044. loaded: data.loaded,
  16045. total: data.total
  16046. });
  16047. });
  16048. messageHandler.on("FetchBuiltInCMap", data => {
  16049. if (this.destroyed) {
  16050. return Promise.reject(new Error("Worker was destroyed."));
  16051. }
  16052. if (!this.cMapReaderFactory) {
  16053. return Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."));
  16054. }
  16055. return this.cMapReaderFactory.fetch(data);
  16056. });
  16057. messageHandler.on("FetchStandardFontData", data => {
  16058. if (this.destroyed) {
  16059. return Promise.reject(new Error("Worker was destroyed."));
  16060. }
  16061. if (!this.standardFontDataFactory) {
  16062. return Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."));
  16063. }
  16064. return this.standardFontDataFactory.fetch(data);
  16065. });
  16066. }
  16067. getData() {
  16068. return this.messageHandler.sendWithPromise("GetData", null);
  16069. }
  16070. saveDocument() {
  16071. if (this.annotationStorage.size <= 0) {
  16072. warn("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
  16073. }
  16074. const {
  16075. map,
  16076. transfer
  16077. } = this.annotationStorage.serializable;
  16078. return this.messageHandler.sendWithPromise("SaveDocument", {
  16079. isPureXfa: !!this._htmlForXfa,
  16080. numPages: this._numPages,
  16081. annotationStorage: map,
  16082. filename: this._fullReader?.filename ?? null
  16083. }, transfer).finally(() => {
  16084. this.annotationStorage.resetModified();
  16085. });
  16086. }
  16087. getPage(pageNumber) {
  16088. if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
  16089. return Promise.reject(new Error("Invalid page request."));
  16090. }
  16091. const pageIndex = pageNumber - 1,
  16092. cachedPromise = this.#pagePromises.get(pageIndex);
  16093. if (cachedPromise) {
  16094. return cachedPromise;
  16095. }
  16096. const promise = this.messageHandler.sendWithPromise("GetPage", {
  16097. pageIndex
  16098. }).then(pageInfo => {
  16099. if (this.destroyed) {
  16100. throw new Error("Transport destroyed");
  16101. }
  16102. if (pageInfo.refStr) {
  16103. this.#pageRefCache.set(pageInfo.refStr, pageNumber);
  16104. }
  16105. const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.pdfBug);
  16106. this.#pageCache.set(pageIndex, page);
  16107. return page;
  16108. });
  16109. this.#pagePromises.set(pageIndex, promise);
  16110. return promise;
  16111. }
  16112. getPageIndex(ref) {
  16113. if (!isRefProxy(ref)) {
  16114. return Promise.reject(new Error("Invalid pageIndex request."));
  16115. }
  16116. return this.messageHandler.sendWithPromise("GetPageIndex", {
  16117. num: ref.num,
  16118. gen: ref.gen
  16119. });
  16120. }
  16121. getAnnotations(pageIndex, intent) {
  16122. return this.messageHandler.sendWithPromise("GetAnnotations", {
  16123. pageIndex,
  16124. intent
  16125. });
  16126. }
  16127. getFieldObjects() {
  16128. return this.#cacheSimpleMethod("GetFieldObjects");
  16129. }
  16130. hasJSActions() {
  16131. return this.#cacheSimpleMethod("HasJSActions");
  16132. }
  16133. getCalculationOrderIds() {
  16134. return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
  16135. }
  16136. getDestinations() {
  16137. return this.messageHandler.sendWithPromise("GetDestinations", null);
  16138. }
  16139. getDestination(id) {
  16140. if (typeof id !== "string") {
  16141. return Promise.reject(new Error("Invalid destination request."));
  16142. }
  16143. return this.messageHandler.sendWithPromise("GetDestination", {
  16144. id
  16145. });
  16146. }
  16147. getPageLabels() {
  16148. return this.messageHandler.sendWithPromise("GetPageLabels", null);
  16149. }
  16150. getPageLayout() {
  16151. return this.messageHandler.sendWithPromise("GetPageLayout", null);
  16152. }
  16153. getPageMode() {
  16154. return this.messageHandler.sendWithPromise("GetPageMode", null);
  16155. }
  16156. getViewerPreferences() {
  16157. return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
  16158. }
  16159. getOpenAction() {
  16160. return this.messageHandler.sendWithPromise("GetOpenAction", null);
  16161. }
  16162. getAttachments() {
  16163. return this.messageHandler.sendWithPromise("GetAttachments", null);
  16164. }
  16165. getDocJSActions() {
  16166. return this.#cacheSimpleMethod("GetDocJSActions");
  16167. }
  16168. getPageJSActions(pageIndex) {
  16169. return this.messageHandler.sendWithPromise("GetPageJSActions", {
  16170. pageIndex
  16171. });
  16172. }
  16173. getStructTree(pageIndex) {
  16174. return this.messageHandler.sendWithPromise("GetStructTree", {
  16175. pageIndex
  16176. });
  16177. }
  16178. getOutline() {
  16179. return this.messageHandler.sendWithPromise("GetOutline", null);
  16180. }
  16181. getOptionalContentConfig(renderingIntent) {
  16182. return this.#cacheSimpleMethod("GetOptionalContentConfig").then(data => new OptionalContentConfig(data, renderingIntent));
  16183. }
  16184. getPermissions() {
  16185. return this.messageHandler.sendWithPromise("GetPermissions", null);
  16186. }
  16187. getMetadata() {
  16188. const name = "GetMetadata",
  16189. cachedPromise = this.#methodPromises.get(name);
  16190. if (cachedPromise) {
  16191. return cachedPromise;
  16192. }
  16193. const promise = this.messageHandler.sendWithPromise(name, null).then(results => ({
  16194. info: results[0],
  16195. metadata: results[1] ? new Metadata(results[1]) : null,
  16196. contentDispositionFilename: this._fullReader?.filename ?? null,
  16197. contentLength: this._fullReader?.contentLength ?? null
  16198. }));
  16199. this.#methodPromises.set(name, promise);
  16200. return promise;
  16201. }
  16202. getMarkInfo() {
  16203. return this.messageHandler.sendWithPromise("GetMarkInfo", null);
  16204. }
  16205. async startCleanup(keepLoadedFonts = false) {
  16206. if (this.destroyed) {
  16207. return;
  16208. }
  16209. await this.messageHandler.sendWithPromise("Cleanup", null);
  16210. for (const page of this.#pageCache.values()) {
  16211. const cleanupSuccessful = page.cleanup();
  16212. if (!cleanupSuccessful) {
  16213. throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`);
  16214. }
  16215. }
  16216. this.commonObjs.clear();
  16217. if (!keepLoadedFonts) {
  16218. this.fontLoader.clear();
  16219. }
  16220. this.#methodPromises.clear();
  16221. this.filterFactory.destroy(true);
  16222. TextLayer.cleanup();
  16223. }
  16224. cachedPageNumber(ref) {
  16225. if (!isRefProxy(ref)) {
  16226. return null;
  16227. }
  16228. const refStr = ref.gen === 0 ? `${ref.num}R` : `${ref.num}R${ref.gen}`;
  16229. return this.#pageRefCache.get(refStr) ?? null;
  16230. }
  16231. }
  16232. const INITIAL_DATA = Symbol("INITIAL_DATA");
  16233. class PDFObjects {
  16234. #objs = Object.create(null);
  16235. #ensureObj(objId) {
  16236. return this.#objs[objId] ||= {
  16237. ...Promise.withResolvers(),
  16238. data: INITIAL_DATA
  16239. };
  16240. }
  16241. get(objId, callback = null) {
  16242. if (callback) {
  16243. const obj = this.#ensureObj(objId);
  16244. obj.promise.then(() => callback(obj.data));
  16245. return null;
  16246. }
  16247. const obj = this.#objs[objId];
  16248. if (!obj || obj.data === INITIAL_DATA) {
  16249. throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
  16250. }
  16251. return obj.data;
  16252. }
  16253. has(objId) {
  16254. const obj = this.#objs[objId];
  16255. return !!obj && obj.data !== INITIAL_DATA;
  16256. }
  16257. resolve(objId, data = null) {
  16258. const obj = this.#ensureObj(objId);
  16259. obj.data = data;
  16260. obj.resolve();
  16261. }
  16262. clear() {
  16263. for (const objId in this.#objs) {
  16264. const {
  16265. data
  16266. } = this.#objs[objId];
  16267. data?.bitmap?.close();
  16268. }
  16269. this.#objs = Object.create(null);
  16270. }
  16271. *[Symbol.iterator]() {
  16272. for (const objId in this.#objs) {
  16273. const {
  16274. data
  16275. } = this.#objs[objId];
  16276. if (data === INITIAL_DATA) {
  16277. continue;
  16278. }
  16279. yield [objId, data];
  16280. }
  16281. }
  16282. }
  16283. class RenderTask {
  16284. #internalRenderTask = null;
  16285. constructor(internalRenderTask) {
  16286. this.#internalRenderTask = internalRenderTask;
  16287. this.onContinue = null;
  16288. }
  16289. get promise() {
  16290. return this.#internalRenderTask.capability.promise;
  16291. }
  16292. cancel(extraDelay = 0) {
  16293. this.#internalRenderTask.cancel(null, extraDelay);
  16294. }
  16295. get separateAnnots() {
  16296. const {
  16297. separateAnnots
  16298. } = this.#internalRenderTask.operatorList;
  16299. if (!separateAnnots) {
  16300. return false;
  16301. }
  16302. const {
  16303. annotationCanvasMap
  16304. } = this.#internalRenderTask;
  16305. return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0;
  16306. }
  16307. }
  16308. class InternalRenderTask {
  16309. #rAF = null;
  16310. static #canvasInUse = new WeakSet();
  16311. constructor({
  16312. callback,
  16313. params,
  16314. objs,
  16315. commonObjs,
  16316. annotationCanvasMap,
  16317. operatorList,
  16318. pageIndex,
  16319. canvasFactory,
  16320. filterFactory,
  16321. useRequestAnimationFrame = false,
  16322. pdfBug = false,
  16323. pageColors = null
  16324. }) {
  16325. this.callback = callback;
  16326. this.params = params;
  16327. this.objs = objs;
  16328. this.commonObjs = commonObjs;
  16329. this.annotationCanvasMap = annotationCanvasMap;
  16330. this.operatorListIdx = null;
  16331. this.operatorList = operatorList;
  16332. this._pageIndex = pageIndex;
  16333. this.canvasFactory = canvasFactory;
  16334. this.filterFactory = filterFactory;
  16335. this._pdfBug = pdfBug;
  16336. this.pageColors = pageColors;
  16337. this.running = false;
  16338. this.graphicsReadyCallback = null;
  16339. this.graphicsReady = false;
  16340. this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
  16341. this.cancelled = false;
  16342. this.capability = Promise.withResolvers();
  16343. this.task = new RenderTask(this);
  16344. this._cancelBound = this.cancel.bind(this);
  16345. this._continueBound = this._continue.bind(this);
  16346. this._scheduleNextBound = this._scheduleNext.bind(this);
  16347. this._nextBound = this._next.bind(this);
  16348. this._canvas = params.canvasContext.canvas;
  16349. }
  16350. get completed() {
  16351. return this.capability.promise.catch(function () {});
  16352. }
  16353. initializeGraphics({
  16354. transparency = false,
  16355. optionalContentConfig
  16356. }) {
  16357. if (this.cancelled) {
  16358. return;
  16359. }
  16360. if (this._canvas) {
  16361. if (InternalRenderTask.#canvasInUse.has(this._canvas)) {
  16362. throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");
  16363. }
  16364. InternalRenderTask.#canvasInUse.add(this._canvas);
  16365. }
  16366. if (this._pdfBug && globalThis.StepperManager?.enabled) {
  16367. this.stepper = globalThis.StepperManager.create(this._pageIndex);
  16368. this.stepper.init(this.operatorList);
  16369. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  16370. }
  16371. const {
  16372. canvasContext,
  16373. viewport,
  16374. transform,
  16375. background
  16376. } = this.params;
  16377. this.gfx = new CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, {
  16378. optionalContentConfig
  16379. }, this.annotationCanvasMap, this.pageColors);
  16380. this.gfx.beginDrawing({
  16381. transform,
  16382. viewport,
  16383. transparency,
  16384. background
  16385. });
  16386. this.operatorListIdx = 0;
  16387. this.graphicsReady = true;
  16388. this.graphicsReadyCallback?.();
  16389. }
  16390. cancel(error = null, extraDelay = 0) {
  16391. this.running = false;
  16392. this.cancelled = true;
  16393. this.gfx?.endDrawing();
  16394. if (this.#rAF) {
  16395. window.cancelAnimationFrame(this.#rAF);
  16396. this.#rAF = null;
  16397. }
  16398. InternalRenderTask.#canvasInUse.delete(this._canvas);
  16399. this.callback(error || new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, extraDelay));
  16400. }
  16401. operatorListChanged() {
  16402. if (!this.graphicsReady) {
  16403. this.graphicsReadyCallback ||= this._continueBound;
  16404. return;
  16405. }
  16406. this.stepper?.updateOperatorList(this.operatorList);
  16407. if (this.running) {
  16408. return;
  16409. }
  16410. this._continue();
  16411. }
  16412. _continue() {
  16413. this.running = true;
  16414. if (this.cancelled) {
  16415. return;
  16416. }
  16417. if (this.task.onContinue) {
  16418. this.task.onContinue(this._scheduleNextBound);
  16419. } else {
  16420. this._scheduleNext();
  16421. }
  16422. }
  16423. _scheduleNext() {
  16424. if (this._useRequestAnimationFrame) {
  16425. this.#rAF = window.requestAnimationFrame(() => {
  16426. this.#rAF = null;
  16427. this._nextBound().catch(this._cancelBound);
  16428. });
  16429. } else {
  16430. Promise.resolve().then(this._nextBound).catch(this._cancelBound);
  16431. }
  16432. }
  16433. async _next() {
  16434. if (this.cancelled) {
  16435. return;
  16436. }
  16437. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
  16438. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  16439. this.running = false;
  16440. if (this.operatorList.lastChunk) {
  16441. this.gfx.endDrawing();
  16442. InternalRenderTask.#canvasInUse.delete(this._canvas);
  16443. this.callback();
  16444. }
  16445. }
  16446. }
  16447. }
  16448. const version = "4.7.76";
  16449. const build = "8b73b828b";
  16450. // EXTERNAL MODULE: ./node_modules/core-js/modules/esnext.iterator.flat-map.js
  16451. var esnext_iterator_flat_map = __webpack_require__(670);
  16452. ;// ./src/shared/scripting_utils.js
  16453. function makeColorComp(n) {
  16454. return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0");
  16455. }
  16456. function scaleAndClamp(x) {
  16457. return Math.max(0, Math.min(255, 255 * x));
  16458. }
  16459. class ColorConverters {
  16460. static CMYK_G([c, y, m, k]) {
  16461. return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];
  16462. }
  16463. static G_CMYK([g]) {
  16464. return ["CMYK", 0, 0, 0, 1 - g];
  16465. }
  16466. static G_RGB([g]) {
  16467. return ["RGB", g, g, g];
  16468. }
  16469. static G_rgb([g]) {
  16470. g = scaleAndClamp(g);
  16471. return [g, g, g];
  16472. }
  16473. static G_HTML([g]) {
  16474. const G = makeColorComp(g);
  16475. return `#${G}${G}${G}`;
  16476. }
  16477. static RGB_G([r, g, b]) {
  16478. return ["G", 0.3 * r + 0.59 * g + 0.11 * b];
  16479. }
  16480. static RGB_rgb(color) {
  16481. return color.map(scaleAndClamp);
  16482. }
  16483. static RGB_HTML(color) {
  16484. return `#${color.map(makeColorComp).join("")}`;
  16485. }
  16486. static T_HTML() {
  16487. return "#00000000";
  16488. }
  16489. static T_rgb() {
  16490. return [null];
  16491. }
  16492. static CMYK_RGB([c, y, m, k]) {
  16493. return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];
  16494. }
  16495. static CMYK_rgb([c, y, m, k]) {
  16496. return [scaleAndClamp(1 - Math.min(1, c + k)), scaleAndClamp(1 - Math.min(1, m + k)), scaleAndClamp(1 - Math.min(1, y + k))];
  16497. }
  16498. static CMYK_HTML(components) {
  16499. const rgb = this.CMYK_RGB(components).slice(1);
  16500. return this.RGB_HTML(rgb);
  16501. }
  16502. static RGB_CMYK([r, g, b]) {
  16503. const c = 1 - r;
  16504. const m = 1 - g;
  16505. const y = 1 - b;
  16506. const k = Math.min(c, m, y);
  16507. return ["CMYK", c, m, y, k];
  16508. }
  16509. }
  16510. ;// ./src/display/xfa_layer.js
  16511. class XfaLayer {
  16512. static setupStorage(html, id, element, storage, intent) {
  16513. const storedData = storage.getValue(id, {
  16514. value: null
  16515. });
  16516. switch (element.name) {
  16517. case "textarea":
  16518. if (storedData.value !== null) {
  16519. html.textContent = storedData.value;
  16520. }
  16521. if (intent === "print") {
  16522. break;
  16523. }
  16524. html.addEventListener("input", event => {
  16525. storage.setValue(id, {
  16526. value: event.target.value
  16527. });
  16528. });
  16529. break;
  16530. case "input":
  16531. if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
  16532. if (storedData.value === element.attributes.xfaOn) {
  16533. html.setAttribute("checked", true);
  16534. } else if (storedData.value === element.attributes.xfaOff) {
  16535. html.removeAttribute("checked");
  16536. }
  16537. if (intent === "print") {
  16538. break;
  16539. }
  16540. html.addEventListener("change", event => {
  16541. storage.setValue(id, {
  16542. value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff")
  16543. });
  16544. });
  16545. } else {
  16546. if (storedData.value !== null) {
  16547. html.setAttribute("value", storedData.value);
  16548. }
  16549. if (intent === "print") {
  16550. break;
  16551. }
  16552. html.addEventListener("input", event => {
  16553. storage.setValue(id, {
  16554. value: event.target.value
  16555. });
  16556. });
  16557. }
  16558. break;
  16559. case "select":
  16560. if (storedData.value !== null) {
  16561. html.setAttribute("value", storedData.value);
  16562. for (const option of element.children) {
  16563. if (option.attributes.value === storedData.value) {
  16564. option.attributes.selected = true;
  16565. } else if (option.attributes.hasOwnProperty("selected")) {
  16566. delete option.attributes.selected;
  16567. }
  16568. }
  16569. }
  16570. html.addEventListener("input", event => {
  16571. const options = event.target.options;
  16572. const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
  16573. storage.setValue(id, {
  16574. value
  16575. });
  16576. });
  16577. break;
  16578. }
  16579. }
  16580. static setAttributes({
  16581. html,
  16582. element,
  16583. storage = null,
  16584. intent,
  16585. linkService
  16586. }) {
  16587. const {
  16588. attributes
  16589. } = element;
  16590. const isHTMLAnchorElement = html instanceof HTMLAnchorElement;
  16591. if (attributes.type === "radio") {
  16592. attributes.name = `${attributes.name}-${intent}`;
  16593. }
  16594. for (const [key, value] of Object.entries(attributes)) {
  16595. if (value === null || value === undefined) {
  16596. continue;
  16597. }
  16598. switch (key) {
  16599. case "class":
  16600. if (value.length) {
  16601. html.setAttribute(key, value.join(" "));
  16602. }
  16603. break;
  16604. case "dataId":
  16605. break;
  16606. case "id":
  16607. html.setAttribute("data-element-id", value);
  16608. break;
  16609. case "style":
  16610. Object.assign(html.style, value);
  16611. break;
  16612. case "textContent":
  16613. html.textContent = value;
  16614. break;
  16615. default:
  16616. if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") {
  16617. html.setAttribute(key, value);
  16618. }
  16619. }
  16620. }
  16621. if (isHTMLAnchorElement) {
  16622. linkService.addLinkAttributes(html, attributes.href, attributes.newWindow);
  16623. }
  16624. if (storage && attributes.dataId) {
  16625. this.setupStorage(html, attributes.dataId, element, storage);
  16626. }
  16627. }
  16628. static render(parameters) {
  16629. const storage = parameters.annotationStorage;
  16630. const linkService = parameters.linkService;
  16631. const root = parameters.xfaHtml;
  16632. const intent = parameters.intent || "display";
  16633. const rootHtml = document.createElement(root.name);
  16634. if (root.attributes) {
  16635. this.setAttributes({
  16636. html: rootHtml,
  16637. element: root,
  16638. intent,
  16639. linkService
  16640. });
  16641. }
  16642. const isNotForRichText = intent !== "richText";
  16643. const rootDiv = parameters.div;
  16644. rootDiv.append(rootHtml);
  16645. if (parameters.viewport) {
  16646. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  16647. rootDiv.style.transform = transform;
  16648. }
  16649. if (isNotForRichText) {
  16650. rootDiv.setAttribute("class", "xfaLayer xfaFont");
  16651. }
  16652. const textDivs = [];
  16653. if (root.children.length === 0) {
  16654. if (root.value) {
  16655. const node = document.createTextNode(root.value);
  16656. rootHtml.append(node);
  16657. if (isNotForRichText && XfaText.shouldBuildText(root.name)) {
  16658. textDivs.push(node);
  16659. }
  16660. }
  16661. return {
  16662. textDivs
  16663. };
  16664. }
  16665. const stack = [[root, -1, rootHtml]];
  16666. while (stack.length > 0) {
  16667. const [parent, i, html] = stack.at(-1);
  16668. if (i + 1 === parent.children.length) {
  16669. stack.pop();
  16670. continue;
  16671. }
  16672. const child = parent.children[++stack.at(-1)[1]];
  16673. if (child === null) {
  16674. continue;
  16675. }
  16676. const {
  16677. name
  16678. } = child;
  16679. if (name === "#text") {
  16680. const node = document.createTextNode(child.value);
  16681. textDivs.push(node);
  16682. html.append(node);
  16683. continue;
  16684. }
  16685. const childHtml = child?.attributes?.xmlns ? document.createElementNS(child.attributes.xmlns, name) : document.createElement(name);
  16686. html.append(childHtml);
  16687. if (child.attributes) {
  16688. this.setAttributes({
  16689. html: childHtml,
  16690. element: child,
  16691. storage,
  16692. intent,
  16693. linkService
  16694. });
  16695. }
  16696. if (child.children?.length > 0) {
  16697. stack.push([child, -1, childHtml]);
  16698. } else if (child.value) {
  16699. const node = document.createTextNode(child.value);
  16700. if (isNotForRichText && XfaText.shouldBuildText(name)) {
  16701. textDivs.push(node);
  16702. }
  16703. childHtml.append(node);
  16704. }
  16705. }
  16706. for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) {
  16707. el.setAttribute("readOnly", true);
  16708. }
  16709. return {
  16710. textDivs
  16711. };
  16712. }
  16713. static update(parameters) {
  16714. const transform = `matrix(${parameters.viewport.transform.join(",")})`;
  16715. parameters.div.style.transform = transform;
  16716. parameters.div.hidden = false;
  16717. }
  16718. }
  16719. ;// ./src/display/annotation_layer.js
  16720. const DEFAULT_TAB_INDEX = 1000;
  16721. const annotation_layer_DEFAULT_FONT_SIZE = 9;
  16722. const GetElementsByNameSet = new WeakSet();
  16723. function getRectDims(rect) {
  16724. return {
  16725. width: rect[2] - rect[0],
  16726. height: rect[3] - rect[1]
  16727. };
  16728. }
  16729. class AnnotationElementFactory {
  16730. static create(parameters) {
  16731. const subtype = parameters.data.annotationType;
  16732. switch (subtype) {
  16733. case AnnotationType.LINK:
  16734. return new LinkAnnotationElement(parameters);
  16735. case AnnotationType.TEXT:
  16736. return new TextAnnotationElement(parameters);
  16737. case AnnotationType.WIDGET:
  16738. const fieldType = parameters.data.fieldType;
  16739. switch (fieldType) {
  16740. case "Tx":
  16741. return new TextWidgetAnnotationElement(parameters);
  16742. case "Btn":
  16743. if (parameters.data.radioButton) {
  16744. return new RadioButtonWidgetAnnotationElement(parameters);
  16745. } else if (parameters.data.checkBox) {
  16746. return new CheckboxWidgetAnnotationElement(parameters);
  16747. }
  16748. return new PushButtonWidgetAnnotationElement(parameters);
  16749. case "Ch":
  16750. return new ChoiceWidgetAnnotationElement(parameters);
  16751. case "Sig":
  16752. return new SignatureWidgetAnnotationElement(parameters);
  16753. }
  16754. return new WidgetAnnotationElement(parameters);
  16755. case AnnotationType.POPUP:
  16756. return new PopupAnnotationElement(parameters);
  16757. case AnnotationType.FREETEXT:
  16758. return new FreeTextAnnotationElement(parameters);
  16759. case AnnotationType.LINE:
  16760. return new LineAnnotationElement(parameters);
  16761. case AnnotationType.SQUARE:
  16762. return new SquareAnnotationElement(parameters);
  16763. case AnnotationType.CIRCLE:
  16764. return new CircleAnnotationElement(parameters);
  16765. case AnnotationType.POLYLINE:
  16766. return new PolylineAnnotationElement(parameters);
  16767. case AnnotationType.CARET:
  16768. return new CaretAnnotationElement(parameters);
  16769. case AnnotationType.INK:
  16770. return new InkAnnotationElement(parameters);
  16771. case AnnotationType.POLYGON:
  16772. return new PolygonAnnotationElement(parameters);
  16773. case AnnotationType.HIGHLIGHT:
  16774. return new HighlightAnnotationElement(parameters);
  16775. case AnnotationType.UNDERLINE:
  16776. return new UnderlineAnnotationElement(parameters);
  16777. case AnnotationType.SQUIGGLY:
  16778. return new SquigglyAnnotationElement(parameters);
  16779. case AnnotationType.STRIKEOUT:
  16780. return new StrikeOutAnnotationElement(parameters);
  16781. case AnnotationType.STAMP:
  16782. return new StampAnnotationElement(parameters);
  16783. case AnnotationType.FILEATTACHMENT:
  16784. return new FileAttachmentAnnotationElement(parameters);
  16785. default:
  16786. return new AnnotationElement(parameters);
  16787. }
  16788. }
  16789. }
  16790. class AnnotationElement {
  16791. #updates = null;
  16792. #hasBorder = false;
  16793. #popupElement = null;
  16794. constructor(parameters, {
  16795. isRenderable = false,
  16796. ignoreBorder = false,
  16797. createQuadrilaterals = false
  16798. } = {}) {
  16799. this.isRenderable = isRenderable;
  16800. this.data = parameters.data;
  16801. this.layer = parameters.layer;
  16802. this.linkService = parameters.linkService;
  16803. this.downloadManager = parameters.downloadManager;
  16804. this.imageResourcesPath = parameters.imageResourcesPath;
  16805. this.renderForms = parameters.renderForms;
  16806. this.svgFactory = parameters.svgFactory;
  16807. this.annotationStorage = parameters.annotationStorage;
  16808. this.enableScripting = parameters.enableScripting;
  16809. this.hasJSActions = parameters.hasJSActions;
  16810. this._fieldObjects = parameters.fieldObjects;
  16811. this.parent = parameters.parent;
  16812. if (isRenderable) {
  16813. this.container = this._createContainer(ignoreBorder);
  16814. }
  16815. if (createQuadrilaterals) {
  16816. this._createQuadrilaterals();
  16817. }
  16818. }
  16819. static _hasPopupData({
  16820. titleObj,
  16821. contentsObj,
  16822. richText
  16823. }) {
  16824. return !!(titleObj?.str || contentsObj?.str || richText?.str);
  16825. }
  16826. get _isEditable() {
  16827. return this.data.isEditable;
  16828. }
  16829. get hasPopupData() {
  16830. return AnnotationElement._hasPopupData(this.data);
  16831. }
  16832. updateEdited(params) {
  16833. if (!this.container) {
  16834. return;
  16835. }
  16836. this.#updates ||= {
  16837. rect: this.data.rect.slice(0)
  16838. };
  16839. const {
  16840. rect
  16841. } = params;
  16842. if (rect) {
  16843. this.#setRectEdited(rect);
  16844. }
  16845. this.#popupElement?.popup.updateEdited(params);
  16846. }
  16847. resetEdited() {
  16848. if (!this.#updates) {
  16849. return;
  16850. }
  16851. this.#setRectEdited(this.#updates.rect);
  16852. this.#popupElement?.popup.resetEdited();
  16853. this.#updates = null;
  16854. }
  16855. #setRectEdited(rect) {
  16856. const {
  16857. container: {
  16858. style
  16859. },
  16860. data: {
  16861. rect: currentRect,
  16862. rotation
  16863. },
  16864. parent: {
  16865. viewport: {
  16866. rawDims: {
  16867. pageWidth,
  16868. pageHeight,
  16869. pageX,
  16870. pageY
  16871. }
  16872. }
  16873. }
  16874. } = this;
  16875. currentRect?.splice(0, 4, ...rect);
  16876. const {
  16877. width,
  16878. height
  16879. } = getRectDims(rect);
  16880. style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;
  16881. style.top = `${100 * (pageHeight - rect[3] + pageY) / pageHeight}%`;
  16882. if (rotation === 0) {
  16883. style.width = `${100 * width / pageWidth}%`;
  16884. style.height = `${100 * height / pageHeight}%`;
  16885. } else {
  16886. this.setRotation(rotation);
  16887. }
  16888. }
  16889. _createContainer(ignoreBorder) {
  16890. const {
  16891. data,
  16892. parent: {
  16893. page,
  16894. viewport
  16895. }
  16896. } = this;
  16897. const container = document.createElement("section");
  16898. container.setAttribute("data-annotation-id", data.id);
  16899. if (!(this instanceof WidgetAnnotationElement)) {
  16900. container.tabIndex = DEFAULT_TAB_INDEX;
  16901. }
  16902. const {
  16903. style
  16904. } = container;
  16905. style.zIndex = this.parent.zIndex++;
  16906. if (data.popupRef) {
  16907. container.setAttribute("aria-haspopup", "dialog");
  16908. }
  16909. if (data.alternativeText) {
  16910. container.title = data.alternativeText;
  16911. }
  16912. if (data.noRotate) {
  16913. container.classList.add("norotate");
  16914. }
  16915. if (!data.rect || this instanceof PopupAnnotationElement) {
  16916. const {
  16917. rotation
  16918. } = data;
  16919. if (!data.hasOwnCanvas && rotation !== 0) {
  16920. this.setRotation(rotation, container);
  16921. }
  16922. return container;
  16923. }
  16924. const {
  16925. width,
  16926. height
  16927. } = getRectDims(data.rect);
  16928. if (!ignoreBorder && data.borderStyle.width > 0) {
  16929. style.borderWidth = `${data.borderStyle.width}px`;
  16930. const horizontalRadius = data.borderStyle.horizontalCornerRadius;
  16931. const verticalRadius = data.borderStyle.verticalCornerRadius;
  16932. if (horizontalRadius > 0 || verticalRadius > 0) {
  16933. const radius = `calc(${horizontalRadius}px * var(--scale-factor)) / calc(${verticalRadius}px * var(--scale-factor))`;
  16934. style.borderRadius = radius;
  16935. } else if (this instanceof RadioButtonWidgetAnnotationElement) {
  16936. const radius = `calc(${width}px * var(--scale-factor)) / calc(${height}px * var(--scale-factor))`;
  16937. style.borderRadius = radius;
  16938. }
  16939. switch (data.borderStyle.style) {
  16940. case AnnotationBorderStyleType.SOLID:
  16941. style.borderStyle = "solid";
  16942. break;
  16943. case AnnotationBorderStyleType.DASHED:
  16944. style.borderStyle = "dashed";
  16945. break;
  16946. case AnnotationBorderStyleType.BEVELED:
  16947. warn("Unimplemented border style: beveled");
  16948. break;
  16949. case AnnotationBorderStyleType.INSET:
  16950. warn("Unimplemented border style: inset");
  16951. break;
  16952. case AnnotationBorderStyleType.UNDERLINE:
  16953. style.borderBottomStyle = "solid";
  16954. break;
  16955. default:
  16956. break;
  16957. }
  16958. const borderColor = data.borderColor || null;
  16959. if (borderColor) {
  16960. this.#hasBorder = true;
  16961. style.borderColor = Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0);
  16962. } else {
  16963. style.borderWidth = 0;
  16964. }
  16965. }
  16966. const rect = Util.normalizeRect([data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1]]);
  16967. const {
  16968. pageWidth,
  16969. pageHeight,
  16970. pageX,
  16971. pageY
  16972. } = viewport.rawDims;
  16973. style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;
  16974. style.top = `${100 * (rect[1] - pageY) / pageHeight}%`;
  16975. const {
  16976. rotation
  16977. } = data;
  16978. if (data.hasOwnCanvas || rotation === 0) {
  16979. style.width = `${100 * width / pageWidth}%`;
  16980. style.height = `${100 * height / pageHeight}%`;
  16981. } else {
  16982. this.setRotation(rotation, container);
  16983. }
  16984. return container;
  16985. }
  16986. setRotation(angle, container = this.container) {
  16987. if (!this.data.rect) {
  16988. return;
  16989. }
  16990. const {
  16991. pageWidth,
  16992. pageHeight
  16993. } = this.parent.viewport.rawDims;
  16994. const {
  16995. width,
  16996. height
  16997. } = getRectDims(this.data.rect);
  16998. let elementWidth, elementHeight;
  16999. if (angle % 180 === 0) {
  17000. elementWidth = 100 * width / pageWidth;
  17001. elementHeight = 100 * height / pageHeight;
  17002. } else {
  17003. elementWidth = 100 * height / pageWidth;
  17004. elementHeight = 100 * width / pageHeight;
  17005. }
  17006. container.style.width = `${elementWidth}%`;
  17007. container.style.height = `${elementHeight}%`;
  17008. container.setAttribute("data-main-rotation", (360 - angle) % 360);
  17009. }
  17010. get _commonActions() {
  17011. const setColor = (jsName, styleName, event) => {
  17012. const color = event.detail[jsName];
  17013. const colorType = color[0];
  17014. const colorArray = color.slice(1);
  17015. event.target.style[styleName] = ColorConverters[`${colorType}_HTML`](colorArray);
  17016. this.annotationStorage.setValue(this.data.id, {
  17017. [styleName]: ColorConverters[`${colorType}_rgb`](colorArray)
  17018. });
  17019. };
  17020. return shadow(this, "_commonActions", {
  17021. display: event => {
  17022. const {
  17023. display
  17024. } = event.detail;
  17025. const hidden = display % 2 === 1;
  17026. this.container.style.visibility = hidden ? "hidden" : "visible";
  17027. this.annotationStorage.setValue(this.data.id, {
  17028. noView: hidden,
  17029. noPrint: display === 1 || display === 2
  17030. });
  17031. },
  17032. print: event => {
  17033. this.annotationStorage.setValue(this.data.id, {
  17034. noPrint: !event.detail.print
  17035. });
  17036. },
  17037. hidden: event => {
  17038. const {
  17039. hidden
  17040. } = event.detail;
  17041. this.container.style.visibility = hidden ? "hidden" : "visible";
  17042. this.annotationStorage.setValue(this.data.id, {
  17043. noPrint: hidden,
  17044. noView: hidden
  17045. });
  17046. },
  17047. focus: event => {
  17048. setTimeout(() => event.target.focus({
  17049. preventScroll: false
  17050. }), 0);
  17051. },
  17052. userName: event => {
  17053. event.target.title = event.detail.userName;
  17054. },
  17055. readonly: event => {
  17056. event.target.disabled = event.detail.readonly;
  17057. },
  17058. required: event => {
  17059. this._setRequired(event.target, event.detail.required);
  17060. },
  17061. bgColor: event => {
  17062. setColor("bgColor", "backgroundColor", event);
  17063. },
  17064. fillColor: event => {
  17065. setColor("fillColor", "backgroundColor", event);
  17066. },
  17067. fgColor: event => {
  17068. setColor("fgColor", "color", event);
  17069. },
  17070. textColor: event => {
  17071. setColor("textColor", "color", event);
  17072. },
  17073. borderColor: event => {
  17074. setColor("borderColor", "borderColor", event);
  17075. },
  17076. strokeColor: event => {
  17077. setColor("strokeColor", "borderColor", event);
  17078. },
  17079. rotation: event => {
  17080. const angle = event.detail.rotation;
  17081. this.setRotation(angle);
  17082. this.annotationStorage.setValue(this.data.id, {
  17083. rotation: angle
  17084. });
  17085. }
  17086. });
  17087. }
  17088. _dispatchEventFromSandbox(actions, jsEvent) {
  17089. const commonActions = this._commonActions;
  17090. for (const name of Object.keys(jsEvent.detail)) {
  17091. const action = actions[name] || commonActions[name];
  17092. action?.(jsEvent);
  17093. }
  17094. }
  17095. _setDefaultPropertiesFromJS(element) {
  17096. if (!this.enableScripting) {
  17097. return;
  17098. }
  17099. const storedData = this.annotationStorage.getRawValue(this.data.id);
  17100. if (!storedData) {
  17101. return;
  17102. }
  17103. const commonActions = this._commonActions;
  17104. for (const [actionName, detail] of Object.entries(storedData)) {
  17105. const action = commonActions[actionName];
  17106. if (action) {
  17107. const eventProxy = {
  17108. detail: {
  17109. [actionName]: detail
  17110. },
  17111. target: element
  17112. };
  17113. action(eventProxy);
  17114. delete storedData[actionName];
  17115. }
  17116. }
  17117. }
  17118. _createQuadrilaterals() {
  17119. if (!this.container) {
  17120. return;
  17121. }
  17122. const {
  17123. quadPoints
  17124. } = this.data;
  17125. if (!quadPoints) {
  17126. return;
  17127. }
  17128. const [rectBlX, rectBlY, rectTrX, rectTrY] = this.data.rect.map(x => Math.fround(x));
  17129. if (quadPoints.length === 8) {
  17130. const [trX, trY, blX, blY] = quadPoints.subarray(2, 6);
  17131. if (rectTrX === trX && rectTrY === trY && rectBlX === blX && rectBlY === blY) {
  17132. return;
  17133. }
  17134. }
  17135. const {
  17136. style
  17137. } = this.container;
  17138. let svgBuffer;
  17139. if (this.#hasBorder) {
  17140. const {
  17141. borderColor,
  17142. borderWidth
  17143. } = style;
  17144. style.borderWidth = 0;
  17145. svgBuffer = ["url('data:image/svg+xml;utf8,", `<svg xmlns="http://www.w3.org/2000/svg"`, ` preserveAspectRatio="none" viewBox="0 0 1 1">`, `<g fill="transparent" stroke="${borderColor}" stroke-width="${borderWidth}">`];
  17146. this.container.classList.add("hasBorder");
  17147. }
  17148. const width = rectTrX - rectBlX;
  17149. const height = rectTrY - rectBlY;
  17150. const {
  17151. svgFactory
  17152. } = this;
  17153. const svg = svgFactory.createElement("svg");
  17154. svg.classList.add("quadrilateralsContainer");
  17155. svg.setAttribute("width", 0);
  17156. svg.setAttribute("height", 0);
  17157. const defs = svgFactory.createElement("defs");
  17158. svg.append(defs);
  17159. const clipPath = svgFactory.createElement("clipPath");
  17160. const id = `clippath_${this.data.id}`;
  17161. clipPath.setAttribute("id", id);
  17162. clipPath.setAttribute("clipPathUnits", "objectBoundingBox");
  17163. defs.append(clipPath);
  17164. for (let i = 2, ii = quadPoints.length; i < ii; i += 8) {
  17165. const trX = quadPoints[i];
  17166. const trY = quadPoints[i + 1];
  17167. const blX = quadPoints[i + 2];
  17168. const blY = quadPoints[i + 3];
  17169. const rect = svgFactory.createElement("rect");
  17170. const x = (blX - rectBlX) / width;
  17171. const y = (rectTrY - trY) / height;
  17172. const rectWidth = (trX - blX) / width;
  17173. const rectHeight = (trY - blY) / height;
  17174. rect.setAttribute("x", x);
  17175. rect.setAttribute("y", y);
  17176. rect.setAttribute("width", rectWidth);
  17177. rect.setAttribute("height", rectHeight);
  17178. clipPath.append(rect);
  17179. svgBuffer?.push(`<rect vector-effect="non-scaling-stroke" x="${x}" y="${y}" width="${rectWidth}" height="${rectHeight}"/>`);
  17180. }
  17181. if (this.#hasBorder) {
  17182. svgBuffer.push(`</g></svg>')`);
  17183. style.backgroundImage = svgBuffer.join("");
  17184. }
  17185. this.container.append(svg);
  17186. this.container.style.clipPath = `url(#${id})`;
  17187. }
  17188. _createPopup() {
  17189. const {
  17190. container,
  17191. data
  17192. } = this;
  17193. container.setAttribute("aria-haspopup", "dialog");
  17194. const popup = this.#popupElement = new PopupAnnotationElement({
  17195. data: {
  17196. color: data.color,
  17197. titleObj: data.titleObj,
  17198. modificationDate: data.modificationDate,
  17199. contentsObj: data.contentsObj,
  17200. richText: data.richText,
  17201. parentRect: data.rect,
  17202. borderStyle: 0,
  17203. id: `popup_${data.id}`,
  17204. rotation: data.rotation
  17205. },
  17206. parent: this.parent,
  17207. elements: [this]
  17208. });
  17209. this.parent.div.append(popup.render());
  17210. }
  17211. render() {
  17212. unreachable("Abstract method `AnnotationElement.render` called");
  17213. }
  17214. _getElementsByName(name, skipId = null) {
  17215. const fields = [];
  17216. if (this._fieldObjects) {
  17217. const fieldObj = this._fieldObjects[name];
  17218. if (fieldObj) {
  17219. for (const {
  17220. page,
  17221. id,
  17222. exportValues
  17223. } of fieldObj) {
  17224. if (page === -1) {
  17225. continue;
  17226. }
  17227. if (id === skipId) {
  17228. continue;
  17229. }
  17230. const exportValue = typeof exportValues === "string" ? exportValues : null;
  17231. const domElement = document.querySelector(`[data-element-id="${id}"]`);
  17232. if (domElement && !GetElementsByNameSet.has(domElement)) {
  17233. warn(`_getElementsByName - element not allowed: ${id}`);
  17234. continue;
  17235. }
  17236. fields.push({
  17237. id,
  17238. exportValue,
  17239. domElement
  17240. });
  17241. }
  17242. }
  17243. return fields;
  17244. }
  17245. for (const domElement of document.getElementsByName(name)) {
  17246. const {
  17247. exportValue
  17248. } = domElement;
  17249. const id = domElement.getAttribute("data-element-id");
  17250. if (id === skipId) {
  17251. continue;
  17252. }
  17253. if (!GetElementsByNameSet.has(domElement)) {
  17254. continue;
  17255. }
  17256. fields.push({
  17257. id,
  17258. exportValue,
  17259. domElement
  17260. });
  17261. }
  17262. return fields;
  17263. }
  17264. show() {
  17265. if (this.container) {
  17266. this.container.hidden = false;
  17267. }
  17268. this.popup?.maybeShow();
  17269. }
  17270. hide() {
  17271. if (this.container) {
  17272. this.container.hidden = true;
  17273. }
  17274. this.popup?.forceHide();
  17275. }
  17276. getElementsToTriggerPopup() {
  17277. return this.container;
  17278. }
  17279. addHighlightArea() {
  17280. const triggers = this.getElementsToTriggerPopup();
  17281. if (Array.isArray(triggers)) {
  17282. for (const element of triggers) {
  17283. element.classList.add("highlightArea");
  17284. }
  17285. } else {
  17286. triggers.classList.add("highlightArea");
  17287. }
  17288. }
  17289. _editOnDoubleClick() {
  17290. if (!this._isEditable) {
  17291. return;
  17292. }
  17293. const {
  17294. annotationEditorType: mode,
  17295. data: {
  17296. id: editId
  17297. }
  17298. } = this;
  17299. this.container.addEventListener("dblclick", () => {
  17300. this.linkService.eventBus?.dispatch("switchannotationeditormode", {
  17301. source: this,
  17302. mode,
  17303. editId
  17304. });
  17305. });
  17306. }
  17307. }
  17308. class LinkAnnotationElement extends AnnotationElement {
  17309. constructor(parameters, options = null) {
  17310. super(parameters, {
  17311. isRenderable: true,
  17312. ignoreBorder: !!options?.ignoreBorder,
  17313. createQuadrilaterals: true
  17314. });
  17315. this.isTooltipOnly = parameters.data.isTooltipOnly;
  17316. }
  17317. render() {
  17318. const {
  17319. data,
  17320. linkService
  17321. } = this;
  17322. const link = document.createElement("a");
  17323. link.setAttribute("data-element-id", data.id);
  17324. let isBound = false;
  17325. if (data.url) {
  17326. linkService.addLinkAttributes(link, data.url, data.newWindow);
  17327. isBound = true;
  17328. } else if (data.action) {
  17329. this._bindNamedAction(link, data.action);
  17330. isBound = true;
  17331. } else if (data.attachment) {
  17332. this.#bindAttachment(link, data.attachment, data.attachmentDest);
  17333. isBound = true;
  17334. } else if (data.setOCGState) {
  17335. this.#bindSetOCGState(link, data.setOCGState);
  17336. isBound = true;
  17337. } else if (data.dest) {
  17338. this._bindLink(link, data.dest);
  17339. isBound = true;
  17340. } else {
  17341. if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {
  17342. this._bindJSAction(link, data);
  17343. isBound = true;
  17344. }
  17345. if (data.resetForm) {
  17346. this._bindResetFormAction(link, data.resetForm);
  17347. isBound = true;
  17348. } else if (this.isTooltipOnly && !isBound) {
  17349. this._bindLink(link, "");
  17350. isBound = true;
  17351. }
  17352. }
  17353. this.container.classList.add("linkAnnotation");
  17354. if (isBound) {
  17355. this.container.append(link);
  17356. }
  17357. return this.container;
  17358. }
  17359. #setInternalLink() {
  17360. this.container.setAttribute("data-internal-link", "");
  17361. }
  17362. _bindLink(link, destination) {
  17363. link.href = this.linkService.getDestinationHash(destination);
  17364. link.onclick = () => {
  17365. if (destination) {
  17366. this.linkService.goToDestination(destination);
  17367. }
  17368. return false;
  17369. };
  17370. if (destination || destination === "") {
  17371. this.#setInternalLink();
  17372. }
  17373. }
  17374. _bindNamedAction(link, action) {
  17375. link.href = this.linkService.getAnchorUrl("");
  17376. link.onclick = () => {
  17377. this.linkService.executeNamedAction(action);
  17378. return false;
  17379. };
  17380. this.#setInternalLink();
  17381. }
  17382. #bindAttachment(link, attachment, dest = null) {
  17383. link.href = this.linkService.getAnchorUrl("");
  17384. if (attachment.description) {
  17385. link.title = attachment.description;
  17386. }
  17387. link.onclick = () => {
  17388. this.downloadManager?.openOrDownloadData(attachment.content, attachment.filename, dest);
  17389. return false;
  17390. };
  17391. this.#setInternalLink();
  17392. }
  17393. #bindSetOCGState(link, action) {
  17394. link.href = this.linkService.getAnchorUrl("");
  17395. link.onclick = () => {
  17396. this.linkService.executeSetOCGState(action);
  17397. return false;
  17398. };
  17399. this.#setInternalLink();
  17400. }
  17401. _bindJSAction(link, data) {
  17402. link.href = this.linkService.getAnchorUrl("");
  17403. const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);
  17404. for (const name of Object.keys(data.actions)) {
  17405. const jsName = map.get(name);
  17406. if (!jsName) {
  17407. continue;
  17408. }
  17409. link[jsName] = () => {
  17410. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  17411. source: this,
  17412. detail: {
  17413. id: data.id,
  17414. name
  17415. }
  17416. });
  17417. return false;
  17418. };
  17419. }
  17420. if (!link.onclick) {
  17421. link.onclick = () => false;
  17422. }
  17423. this.#setInternalLink();
  17424. }
  17425. _bindResetFormAction(link, resetForm) {
  17426. const otherClickAction = link.onclick;
  17427. if (!otherClickAction) {
  17428. link.href = this.linkService.getAnchorUrl("");
  17429. }
  17430. this.#setInternalLink();
  17431. if (!this._fieldObjects) {
  17432. warn(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided.");
  17433. if (!otherClickAction) {
  17434. link.onclick = () => false;
  17435. }
  17436. return;
  17437. }
  17438. link.onclick = () => {
  17439. otherClickAction?.();
  17440. const {
  17441. fields: resetFormFields,
  17442. refs: resetFormRefs,
  17443. include
  17444. } = resetForm;
  17445. const allFields = [];
  17446. if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) {
  17447. const fieldIds = new Set(resetFormRefs);
  17448. for (const fieldName of resetFormFields) {
  17449. const fields = this._fieldObjects[fieldName] || [];
  17450. for (const {
  17451. id
  17452. } of fields) {
  17453. fieldIds.add(id);
  17454. }
  17455. }
  17456. for (const fields of Object.values(this._fieldObjects)) {
  17457. for (const field of fields) {
  17458. if (fieldIds.has(field.id) === include) {
  17459. allFields.push(field);
  17460. }
  17461. }
  17462. }
  17463. } else {
  17464. for (const fields of Object.values(this._fieldObjects)) {
  17465. allFields.push(...fields);
  17466. }
  17467. }
  17468. const storage = this.annotationStorage;
  17469. const allIds = [];
  17470. for (const field of allFields) {
  17471. const {
  17472. id
  17473. } = field;
  17474. allIds.push(id);
  17475. switch (field.type) {
  17476. case "text":
  17477. {
  17478. const value = field.defaultValue || "";
  17479. storage.setValue(id, {
  17480. value
  17481. });
  17482. break;
  17483. }
  17484. case "checkbox":
  17485. case "radiobutton":
  17486. {
  17487. const value = field.defaultValue === field.exportValues;
  17488. storage.setValue(id, {
  17489. value
  17490. });
  17491. break;
  17492. }
  17493. case "combobox":
  17494. case "listbox":
  17495. {
  17496. const value = field.defaultValue || "";
  17497. storage.setValue(id, {
  17498. value
  17499. });
  17500. break;
  17501. }
  17502. default:
  17503. continue;
  17504. }
  17505. const domElement = document.querySelector(`[data-element-id="${id}"]`);
  17506. if (!domElement) {
  17507. continue;
  17508. } else if (!GetElementsByNameSet.has(domElement)) {
  17509. warn(`_bindResetFormAction - element not allowed: ${id}`);
  17510. continue;
  17511. }
  17512. domElement.dispatchEvent(new Event("resetform"));
  17513. }
  17514. if (this.enableScripting) {
  17515. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  17516. source: this,
  17517. detail: {
  17518. id: "app",
  17519. ids: allIds,
  17520. name: "ResetForm"
  17521. }
  17522. });
  17523. }
  17524. return false;
  17525. };
  17526. }
  17527. }
  17528. class TextAnnotationElement extends AnnotationElement {
  17529. constructor(parameters) {
  17530. super(parameters, {
  17531. isRenderable: true
  17532. });
  17533. }
  17534. render() {
  17535. this.container.classList.add("textAnnotation");
  17536. const image = document.createElement("img");
  17537. image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";
  17538. image.setAttribute("data-l10n-id", "pdfjs-text-annotation-type");
  17539. image.setAttribute("data-l10n-args", JSON.stringify({
  17540. type: this.data.name
  17541. }));
  17542. if (!this.data.popupRef && this.hasPopupData) {
  17543. this._createPopup();
  17544. }
  17545. this.container.append(image);
  17546. return this.container;
  17547. }
  17548. }
  17549. class WidgetAnnotationElement extends AnnotationElement {
  17550. render() {
  17551. return this.container;
  17552. }
  17553. showElementAndHideCanvas(element) {
  17554. if (this.data.hasOwnCanvas) {
  17555. if (element.previousSibling?.nodeName === "CANVAS") {
  17556. element.previousSibling.hidden = true;
  17557. }
  17558. element.hidden = false;
  17559. }
  17560. }
  17561. _getKeyModifier(event) {
  17562. return util_FeatureTest.platform.isMac ? event.metaKey : event.ctrlKey;
  17563. }
  17564. _setEventListener(element, elementData, baseName, eventName, valueGetter) {
  17565. if (baseName.includes("mouse")) {
  17566. element.addEventListener(baseName, event => {
  17567. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  17568. source: this,
  17569. detail: {
  17570. id: this.data.id,
  17571. name: eventName,
  17572. value: valueGetter(event),
  17573. shift: event.shiftKey,
  17574. modifier: this._getKeyModifier(event)
  17575. }
  17576. });
  17577. });
  17578. } else {
  17579. element.addEventListener(baseName, event => {
  17580. if (baseName === "blur") {
  17581. if (!elementData.focused || !event.relatedTarget) {
  17582. return;
  17583. }
  17584. elementData.focused = false;
  17585. } else if (baseName === "focus") {
  17586. if (elementData.focused) {
  17587. return;
  17588. }
  17589. elementData.focused = true;
  17590. }
  17591. if (!valueGetter) {
  17592. return;
  17593. }
  17594. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  17595. source: this,
  17596. detail: {
  17597. id: this.data.id,
  17598. name: eventName,
  17599. value: valueGetter(event)
  17600. }
  17601. });
  17602. });
  17603. }
  17604. }
  17605. _setEventListeners(element, elementData, names, getter) {
  17606. for (const [baseName, eventName] of names) {
  17607. if (eventName === "Action" || this.data.actions?.[eventName]) {
  17608. if (eventName === "Focus" || eventName === "Blur") {
  17609. elementData ||= {
  17610. focused: false
  17611. };
  17612. }
  17613. this._setEventListener(element, elementData, baseName, eventName, getter);
  17614. if (eventName === "Focus" && !this.data.actions?.Blur) {
  17615. this._setEventListener(element, elementData, "blur", "Blur", null);
  17616. } else if (eventName === "Blur" && !this.data.actions?.Focus) {
  17617. this._setEventListener(element, elementData, "focus", "Focus", null);
  17618. }
  17619. }
  17620. }
  17621. }
  17622. _setBackgroundColor(element) {
  17623. const color = this.data.backgroundColor || null;
  17624. element.style.backgroundColor = color === null ? "transparent" : Util.makeHexColor(color[0], color[1], color[2]);
  17625. }
  17626. _setTextStyle(element) {
  17627. const TEXT_ALIGNMENT = ["left", "center", "right"];
  17628. const {
  17629. fontColor
  17630. } = this.data.defaultAppearanceData;
  17631. const fontSize = this.data.defaultAppearanceData.fontSize || annotation_layer_DEFAULT_FONT_SIZE;
  17632. const style = element.style;
  17633. let computedFontSize;
  17634. const BORDER_SIZE = 2;
  17635. const roundToOneDecimal = x => Math.round(10 * x) / 10;
  17636. if (this.data.multiLine) {
  17637. const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
  17638. const numberOfLines = Math.round(height / (LINE_FACTOR * fontSize)) || 1;
  17639. const lineHeight = height / numberOfLines;
  17640. computedFontSize = Math.min(fontSize, roundToOneDecimal(lineHeight / LINE_FACTOR));
  17641. } else {
  17642. const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
  17643. computedFontSize = Math.min(fontSize, roundToOneDecimal(height / LINE_FACTOR));
  17644. }
  17645. style.fontSize = `calc(${computedFontSize}px * var(--scale-factor))`;
  17646. style.color = Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
  17647. if (this.data.textAlignment !== null) {
  17648. style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  17649. }
  17650. }
  17651. _setRequired(element, isRequired) {
  17652. if (isRequired) {
  17653. element.setAttribute("required", true);
  17654. } else {
  17655. element.removeAttribute("required");
  17656. }
  17657. element.setAttribute("aria-required", isRequired);
  17658. }
  17659. }
  17660. class TextWidgetAnnotationElement extends WidgetAnnotationElement {
  17661. constructor(parameters) {
  17662. const isRenderable = parameters.renderForms || parameters.data.hasOwnCanvas || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
  17663. super(parameters, {
  17664. isRenderable
  17665. });
  17666. }
  17667. setPropertyOnSiblings(base, key, value, keyInStorage) {
  17668. const storage = this.annotationStorage;
  17669. for (const element of this._getElementsByName(base.name, base.id)) {
  17670. if (element.domElement) {
  17671. element.domElement[key] = value;
  17672. }
  17673. storage.setValue(element.id, {
  17674. [keyInStorage]: value
  17675. });
  17676. }
  17677. }
  17678. render() {
  17679. const storage = this.annotationStorage;
  17680. const id = this.data.id;
  17681. this.container.classList.add("textWidgetAnnotation");
  17682. let element = null;
  17683. if (this.renderForms) {
  17684. const storedData = storage.getValue(id, {
  17685. value: this.data.fieldValue
  17686. });
  17687. let textContent = storedData.value || "";
  17688. const maxLen = storage.getValue(id, {
  17689. charLimit: this.data.maxLen
  17690. }).charLimit;
  17691. if (maxLen && textContent.length > maxLen) {
  17692. textContent = textContent.slice(0, maxLen);
  17693. }
  17694. let fieldFormattedValues = storedData.formattedValue || this.data.textContent?.join("\n") || null;
  17695. if (fieldFormattedValues && this.data.comb) {
  17696. fieldFormattedValues = fieldFormattedValues.replaceAll(/\s+/g, "");
  17697. }
  17698. const elementData = {
  17699. userValue: textContent,
  17700. formattedValue: fieldFormattedValues,
  17701. lastCommittedValue: null,
  17702. commitKey: 1,
  17703. focused: false
  17704. };
  17705. if (this.data.multiLine) {
  17706. element = document.createElement("textarea");
  17707. element.textContent = fieldFormattedValues ?? textContent;
  17708. if (this.data.doNotScroll) {
  17709. element.style.overflowY = "hidden";
  17710. }
  17711. } else {
  17712. element = document.createElement("input");
  17713. element.type = "text";
  17714. element.setAttribute("value", fieldFormattedValues ?? textContent);
  17715. if (this.data.doNotScroll) {
  17716. element.style.overflowX = "hidden";
  17717. }
  17718. }
  17719. if (this.data.hasOwnCanvas) {
  17720. element.hidden = true;
  17721. }
  17722. GetElementsByNameSet.add(element);
  17723. element.setAttribute("data-element-id", id);
  17724. element.disabled = this.data.readOnly;
  17725. element.name = this.data.fieldName;
  17726. element.tabIndex = DEFAULT_TAB_INDEX;
  17727. this._setRequired(element, this.data.required);
  17728. if (maxLen) {
  17729. element.maxLength = maxLen;
  17730. }
  17731. element.addEventListener("input", event => {
  17732. storage.setValue(id, {
  17733. value: event.target.value
  17734. });
  17735. this.setPropertyOnSiblings(element, "value", event.target.value, "value");
  17736. elementData.formattedValue = null;
  17737. });
  17738. element.addEventListener("resetform", event => {
  17739. const defaultValue = this.data.defaultFieldValue ?? "";
  17740. element.value = elementData.userValue = defaultValue;
  17741. elementData.formattedValue = null;
  17742. });
  17743. let blurListener = event => {
  17744. const {
  17745. formattedValue
  17746. } = elementData;
  17747. if (formattedValue !== null && formattedValue !== undefined) {
  17748. event.target.value = formattedValue;
  17749. }
  17750. event.target.scrollLeft = 0;
  17751. };
  17752. if (this.enableScripting && this.hasJSActions) {
  17753. element.addEventListener("focus", event => {
  17754. if (elementData.focused) {
  17755. return;
  17756. }
  17757. const {
  17758. target
  17759. } = event;
  17760. if (elementData.userValue) {
  17761. target.value = elementData.userValue;
  17762. }
  17763. elementData.lastCommittedValue = target.value;
  17764. elementData.commitKey = 1;
  17765. if (!this.data.actions?.Focus) {
  17766. elementData.focused = true;
  17767. }
  17768. });
  17769. element.addEventListener("updatefromsandbox", jsEvent => {
  17770. this.showElementAndHideCanvas(jsEvent.target);
  17771. const actions = {
  17772. value(event) {
  17773. elementData.userValue = event.detail.value ?? "";
  17774. storage.setValue(id, {
  17775. value: elementData.userValue.toString()
  17776. });
  17777. event.target.value = elementData.userValue;
  17778. },
  17779. formattedValue(event) {
  17780. const {
  17781. formattedValue
  17782. } = event.detail;
  17783. elementData.formattedValue = formattedValue;
  17784. if (formattedValue !== null && formattedValue !== undefined && event.target !== document.activeElement) {
  17785. event.target.value = formattedValue;
  17786. }
  17787. storage.setValue(id, {
  17788. formattedValue
  17789. });
  17790. },
  17791. selRange(event) {
  17792. event.target.setSelectionRange(...event.detail.selRange);
  17793. },
  17794. charLimit: event => {
  17795. const {
  17796. charLimit
  17797. } = event.detail;
  17798. const {
  17799. target
  17800. } = event;
  17801. if (charLimit === 0) {
  17802. target.removeAttribute("maxLength");
  17803. return;
  17804. }
  17805. target.setAttribute("maxLength", charLimit);
  17806. let value = elementData.userValue;
  17807. if (!value || value.length <= charLimit) {
  17808. return;
  17809. }
  17810. value = value.slice(0, charLimit);
  17811. target.value = elementData.userValue = value;
  17812. storage.setValue(id, {
  17813. value
  17814. });
  17815. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  17816. source: this,
  17817. detail: {
  17818. id,
  17819. name: "Keystroke",
  17820. value,
  17821. willCommit: true,
  17822. commitKey: 1,
  17823. selStart: target.selectionStart,
  17824. selEnd: target.selectionEnd
  17825. }
  17826. });
  17827. }
  17828. };
  17829. this._dispatchEventFromSandbox(actions, jsEvent);
  17830. });
  17831. element.addEventListener("keydown", event => {
  17832. elementData.commitKey = 1;
  17833. let commitKey = -1;
  17834. if (event.key === "Escape") {
  17835. commitKey = 0;
  17836. } else if (event.key === "Enter" && !this.data.multiLine) {
  17837. commitKey = 2;
  17838. } else if (event.key === "Tab") {
  17839. elementData.commitKey = 3;
  17840. }
  17841. if (commitKey === -1) {
  17842. return;
  17843. }
  17844. const {
  17845. value
  17846. } = event.target;
  17847. if (elementData.lastCommittedValue === value) {
  17848. return;
  17849. }
  17850. elementData.lastCommittedValue = value;
  17851. elementData.userValue = value;
  17852. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  17853. source: this,
  17854. detail: {
  17855. id,
  17856. name: "Keystroke",
  17857. value,
  17858. willCommit: true,
  17859. commitKey,
  17860. selStart: event.target.selectionStart,
  17861. selEnd: event.target.selectionEnd
  17862. }
  17863. });
  17864. });
  17865. const _blurListener = blurListener;
  17866. blurListener = null;
  17867. element.addEventListener("blur", event => {
  17868. if (!elementData.focused || !event.relatedTarget) {
  17869. return;
  17870. }
  17871. if (!this.data.actions?.Blur) {
  17872. elementData.focused = false;
  17873. }
  17874. const {
  17875. value
  17876. } = event.target;
  17877. elementData.userValue = value;
  17878. if (elementData.lastCommittedValue !== value) {
  17879. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  17880. source: this,
  17881. detail: {
  17882. id,
  17883. name: "Keystroke",
  17884. value,
  17885. willCommit: true,
  17886. commitKey: elementData.commitKey,
  17887. selStart: event.target.selectionStart,
  17888. selEnd: event.target.selectionEnd
  17889. }
  17890. });
  17891. }
  17892. _blurListener(event);
  17893. });
  17894. if (this.data.actions?.Keystroke) {
  17895. element.addEventListener("beforeinput", event => {
  17896. elementData.lastCommittedValue = null;
  17897. const {
  17898. data,
  17899. target
  17900. } = event;
  17901. const {
  17902. value,
  17903. selectionStart,
  17904. selectionEnd
  17905. } = target;
  17906. let selStart = selectionStart,
  17907. selEnd = selectionEnd;
  17908. switch (event.inputType) {
  17909. case "deleteWordBackward":
  17910. {
  17911. const match = value.substring(0, selectionStart).match(/\w*[^\w]*$/);
  17912. if (match) {
  17913. selStart -= match[0].length;
  17914. }
  17915. break;
  17916. }
  17917. case "deleteWordForward":
  17918. {
  17919. const match = value.substring(selectionStart).match(/^[^\w]*\w*/);
  17920. if (match) {
  17921. selEnd += match[0].length;
  17922. }
  17923. break;
  17924. }
  17925. case "deleteContentBackward":
  17926. if (selectionStart === selectionEnd) {
  17927. selStart -= 1;
  17928. }
  17929. break;
  17930. case "deleteContentForward":
  17931. if (selectionStart === selectionEnd) {
  17932. selEnd += 1;
  17933. }
  17934. break;
  17935. }
  17936. event.preventDefault();
  17937. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  17938. source: this,
  17939. detail: {
  17940. id,
  17941. name: "Keystroke",
  17942. value,
  17943. change: data || "",
  17944. willCommit: false,
  17945. selStart,
  17946. selEnd
  17947. }
  17948. });
  17949. });
  17950. }
  17951. this._setEventListeners(element, elementData, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value);
  17952. }
  17953. if (blurListener) {
  17954. element.addEventListener("blur", blurListener);
  17955. }
  17956. if (this.data.comb) {
  17957. const fieldWidth = this.data.rect[2] - this.data.rect[0];
  17958. const combWidth = fieldWidth / maxLen;
  17959. element.classList.add("comb");
  17960. element.style.letterSpacing = `calc(${combWidth}px * var(--scale-factor) - 1ch)`;
  17961. }
  17962. } else {
  17963. element = document.createElement("div");
  17964. element.textContent = this.data.fieldValue;
  17965. element.style.verticalAlign = "middle";
  17966. element.style.display = "table-cell";
  17967. if (this.data.hasOwnCanvas) {
  17968. element.hidden = true;
  17969. }
  17970. }
  17971. this._setTextStyle(element);
  17972. this._setBackgroundColor(element);
  17973. this._setDefaultPropertiesFromJS(element);
  17974. this.container.append(element);
  17975. return this.container;
  17976. }
  17977. }
  17978. class SignatureWidgetAnnotationElement extends WidgetAnnotationElement {
  17979. constructor(parameters) {
  17980. super(parameters, {
  17981. isRenderable: !!parameters.data.hasOwnCanvas
  17982. });
  17983. }
  17984. }
  17985. class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement {
  17986. constructor(parameters) {
  17987. super(parameters, {
  17988. isRenderable: parameters.renderForms
  17989. });
  17990. }
  17991. render() {
  17992. const storage = this.annotationStorage;
  17993. const data = this.data;
  17994. const id = data.id;
  17995. let value = storage.getValue(id, {
  17996. value: data.exportValue === data.fieldValue
  17997. }).value;
  17998. if (typeof value === "string") {
  17999. value = value !== "Off";
  18000. storage.setValue(id, {
  18001. value
  18002. });
  18003. }
  18004. this.container.classList.add("buttonWidgetAnnotation", "checkBox");
  18005. const element = document.createElement("input");
  18006. GetElementsByNameSet.add(element);
  18007. element.setAttribute("data-element-id", id);
  18008. element.disabled = data.readOnly;
  18009. this._setRequired(element, this.data.required);
  18010. element.type = "checkbox";
  18011. element.name = data.fieldName;
  18012. if (value) {
  18013. element.setAttribute("checked", true);
  18014. }
  18015. element.setAttribute("exportValue", data.exportValue);
  18016. element.tabIndex = DEFAULT_TAB_INDEX;
  18017. element.addEventListener("change", event => {
  18018. const {
  18019. name,
  18020. checked
  18021. } = event.target;
  18022. for (const checkbox of this._getElementsByName(name, id)) {
  18023. const curChecked = checked && checkbox.exportValue === data.exportValue;
  18024. if (checkbox.domElement) {
  18025. checkbox.domElement.checked = curChecked;
  18026. }
  18027. storage.setValue(checkbox.id, {
  18028. value: curChecked
  18029. });
  18030. }
  18031. storage.setValue(id, {
  18032. value: checked
  18033. });
  18034. });
  18035. element.addEventListener("resetform", event => {
  18036. const defaultValue = data.defaultFieldValue || "Off";
  18037. event.target.checked = defaultValue === data.exportValue;
  18038. });
  18039. if (this.enableScripting && this.hasJSActions) {
  18040. element.addEventListener("updatefromsandbox", jsEvent => {
  18041. const actions = {
  18042. value(event) {
  18043. event.target.checked = event.detail.value !== "Off";
  18044. storage.setValue(id, {
  18045. value: event.target.checked
  18046. });
  18047. }
  18048. };
  18049. this._dispatchEventFromSandbox(actions, jsEvent);
  18050. });
  18051. this._setEventListeners(element, null, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked);
  18052. }
  18053. this._setBackgroundColor(element);
  18054. this._setDefaultPropertiesFromJS(element);
  18055. this.container.append(element);
  18056. return this.container;
  18057. }
  18058. }
  18059. class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement {
  18060. constructor(parameters) {
  18061. super(parameters, {
  18062. isRenderable: parameters.renderForms
  18063. });
  18064. }
  18065. render() {
  18066. this.container.classList.add("buttonWidgetAnnotation", "radioButton");
  18067. const storage = this.annotationStorage;
  18068. const data = this.data;
  18069. const id = data.id;
  18070. let value = storage.getValue(id, {
  18071. value: data.fieldValue === data.buttonValue
  18072. }).value;
  18073. if (typeof value === "string") {
  18074. value = value !== data.buttonValue;
  18075. storage.setValue(id, {
  18076. value
  18077. });
  18078. }
  18079. if (value) {
  18080. for (const radio of this._getElementsByName(data.fieldName, id)) {
  18081. storage.setValue(radio.id, {
  18082. value: false
  18083. });
  18084. }
  18085. }
  18086. const element = document.createElement("input");
  18087. GetElementsByNameSet.add(element);
  18088. element.setAttribute("data-element-id", id);
  18089. element.disabled = data.readOnly;
  18090. this._setRequired(element, this.data.required);
  18091. element.type = "radio";
  18092. element.name = data.fieldName;
  18093. if (value) {
  18094. element.setAttribute("checked", true);
  18095. }
  18096. element.tabIndex = DEFAULT_TAB_INDEX;
  18097. element.addEventListener("change", event => {
  18098. const {
  18099. name,
  18100. checked
  18101. } = event.target;
  18102. for (const radio of this._getElementsByName(name, id)) {
  18103. storage.setValue(radio.id, {
  18104. value: false
  18105. });
  18106. }
  18107. storage.setValue(id, {
  18108. value: checked
  18109. });
  18110. });
  18111. element.addEventListener("resetform", event => {
  18112. const defaultValue = data.defaultFieldValue;
  18113. event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue;
  18114. });
  18115. if (this.enableScripting && this.hasJSActions) {
  18116. const pdfButtonValue = data.buttonValue;
  18117. element.addEventListener("updatefromsandbox", jsEvent => {
  18118. const actions = {
  18119. value: event => {
  18120. const checked = pdfButtonValue === event.detail.value;
  18121. for (const radio of this._getElementsByName(event.target.name)) {
  18122. const curChecked = checked && radio.id === id;
  18123. if (radio.domElement) {
  18124. radio.domElement.checked = curChecked;
  18125. }
  18126. storage.setValue(radio.id, {
  18127. value: curChecked
  18128. });
  18129. }
  18130. }
  18131. };
  18132. this._dispatchEventFromSandbox(actions, jsEvent);
  18133. });
  18134. this._setEventListeners(element, null, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked);
  18135. }
  18136. this._setBackgroundColor(element);
  18137. this._setDefaultPropertiesFromJS(element);
  18138. this.container.append(element);
  18139. return this.container;
  18140. }
  18141. }
  18142. class PushButtonWidgetAnnotationElement extends LinkAnnotationElement {
  18143. constructor(parameters) {
  18144. super(parameters, {
  18145. ignoreBorder: parameters.data.hasAppearance
  18146. });
  18147. }
  18148. render() {
  18149. const container = super.render();
  18150. container.classList.add("buttonWidgetAnnotation", "pushButton");
  18151. const linkElement = container.lastChild;
  18152. if (this.enableScripting && this.hasJSActions && linkElement) {
  18153. this._setDefaultPropertiesFromJS(linkElement);
  18154. linkElement.addEventListener("updatefromsandbox", jsEvent => {
  18155. this._dispatchEventFromSandbox({}, jsEvent);
  18156. });
  18157. }
  18158. return container;
  18159. }
  18160. }
  18161. class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
  18162. constructor(parameters) {
  18163. super(parameters, {
  18164. isRenderable: parameters.renderForms
  18165. });
  18166. }
  18167. render() {
  18168. this.container.classList.add("choiceWidgetAnnotation");
  18169. const storage = this.annotationStorage;
  18170. const id = this.data.id;
  18171. const storedData = storage.getValue(id, {
  18172. value: this.data.fieldValue
  18173. });
  18174. const selectElement = document.createElement("select");
  18175. GetElementsByNameSet.add(selectElement);
  18176. selectElement.setAttribute("data-element-id", id);
  18177. selectElement.disabled = this.data.readOnly;
  18178. this._setRequired(selectElement, this.data.required);
  18179. selectElement.name = this.data.fieldName;
  18180. selectElement.tabIndex = DEFAULT_TAB_INDEX;
  18181. let addAnEmptyEntry = this.data.combo && this.data.options.length > 0;
  18182. if (!this.data.combo) {
  18183. selectElement.size = this.data.options.length;
  18184. if (this.data.multiSelect) {
  18185. selectElement.multiple = true;
  18186. }
  18187. }
  18188. selectElement.addEventListener("resetform", event => {
  18189. const defaultValue = this.data.defaultFieldValue;
  18190. for (const option of selectElement.options) {
  18191. option.selected = option.value === defaultValue;
  18192. }
  18193. });
  18194. for (const option of this.data.options) {
  18195. const optionElement = document.createElement("option");
  18196. optionElement.textContent = option.displayValue;
  18197. optionElement.value = option.exportValue;
  18198. if (storedData.value.includes(option.exportValue)) {
  18199. optionElement.setAttribute("selected", true);
  18200. addAnEmptyEntry = false;
  18201. }
  18202. selectElement.append(optionElement);
  18203. }
  18204. let removeEmptyEntry = null;
  18205. if (addAnEmptyEntry) {
  18206. const noneOptionElement = document.createElement("option");
  18207. noneOptionElement.value = " ";
  18208. noneOptionElement.setAttribute("hidden", true);
  18209. noneOptionElement.setAttribute("selected", true);
  18210. selectElement.prepend(noneOptionElement);
  18211. removeEmptyEntry = () => {
  18212. noneOptionElement.remove();
  18213. selectElement.removeEventListener("input", removeEmptyEntry);
  18214. removeEmptyEntry = null;
  18215. };
  18216. selectElement.addEventListener("input", removeEmptyEntry);
  18217. }
  18218. const getValue = isExport => {
  18219. const name = isExport ? "value" : "textContent";
  18220. const {
  18221. options,
  18222. multiple
  18223. } = selectElement;
  18224. if (!multiple) {
  18225. return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];
  18226. }
  18227. return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]);
  18228. };
  18229. let selectedValues = getValue(false);
  18230. const getItems = event => {
  18231. const options = event.target.options;
  18232. return Array.prototype.map.call(options, option => ({
  18233. displayValue: option.textContent,
  18234. exportValue: option.value
  18235. }));
  18236. };
  18237. if (this.enableScripting && this.hasJSActions) {
  18238. selectElement.addEventListener("updatefromsandbox", jsEvent => {
  18239. const actions = {
  18240. value(event) {
  18241. removeEmptyEntry?.();
  18242. const value = event.detail.value;
  18243. const values = new Set(Array.isArray(value) ? value : [value]);
  18244. for (const option of selectElement.options) {
  18245. option.selected = values.has(option.value);
  18246. }
  18247. storage.setValue(id, {
  18248. value: getValue(true)
  18249. });
  18250. selectedValues = getValue(false);
  18251. },
  18252. multipleSelection(event) {
  18253. selectElement.multiple = true;
  18254. },
  18255. remove(event) {
  18256. const options = selectElement.options;
  18257. const index = event.detail.remove;
  18258. options[index].selected = false;
  18259. selectElement.remove(index);
  18260. if (options.length > 0) {
  18261. const i = Array.prototype.findIndex.call(options, option => option.selected);
  18262. if (i === -1) {
  18263. options[0].selected = true;
  18264. }
  18265. }
  18266. storage.setValue(id, {
  18267. value: getValue(true),
  18268. items: getItems(event)
  18269. });
  18270. selectedValues = getValue(false);
  18271. },
  18272. clear(event) {
  18273. while (selectElement.length !== 0) {
  18274. selectElement.remove(0);
  18275. }
  18276. storage.setValue(id, {
  18277. value: null,
  18278. items: []
  18279. });
  18280. selectedValues = getValue(false);
  18281. },
  18282. insert(event) {
  18283. const {
  18284. index,
  18285. displayValue,
  18286. exportValue
  18287. } = event.detail.insert;
  18288. const selectChild = selectElement.children[index];
  18289. const optionElement = document.createElement("option");
  18290. optionElement.textContent = displayValue;
  18291. optionElement.value = exportValue;
  18292. if (selectChild) {
  18293. selectChild.before(optionElement);
  18294. } else {
  18295. selectElement.append(optionElement);
  18296. }
  18297. storage.setValue(id, {
  18298. value: getValue(true),
  18299. items: getItems(event)
  18300. });
  18301. selectedValues = getValue(false);
  18302. },
  18303. items(event) {
  18304. const {
  18305. items
  18306. } = event.detail;
  18307. while (selectElement.length !== 0) {
  18308. selectElement.remove(0);
  18309. }
  18310. for (const item of items) {
  18311. const {
  18312. displayValue,
  18313. exportValue
  18314. } = item;
  18315. const optionElement = document.createElement("option");
  18316. optionElement.textContent = displayValue;
  18317. optionElement.value = exportValue;
  18318. selectElement.append(optionElement);
  18319. }
  18320. if (selectElement.options.length > 0) {
  18321. selectElement.options[0].selected = true;
  18322. }
  18323. storage.setValue(id, {
  18324. value: getValue(true),
  18325. items: getItems(event)
  18326. });
  18327. selectedValues = getValue(false);
  18328. },
  18329. indices(event) {
  18330. const indices = new Set(event.detail.indices);
  18331. for (const option of event.target.options) {
  18332. option.selected = indices.has(option.index);
  18333. }
  18334. storage.setValue(id, {
  18335. value: getValue(true)
  18336. });
  18337. selectedValues = getValue(false);
  18338. },
  18339. editable(event) {
  18340. event.target.disabled = !event.detail.editable;
  18341. }
  18342. };
  18343. this._dispatchEventFromSandbox(actions, jsEvent);
  18344. });
  18345. selectElement.addEventListener("input", event => {
  18346. const exportValue = getValue(true);
  18347. const change = getValue(false);
  18348. storage.setValue(id, {
  18349. value: exportValue
  18350. });
  18351. event.preventDefault();
  18352. this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
  18353. source: this,
  18354. detail: {
  18355. id,
  18356. name: "Keystroke",
  18357. value: selectedValues,
  18358. change,
  18359. changeEx: exportValue,
  18360. willCommit: false,
  18361. commitKey: 1,
  18362. keyDown: false
  18363. }
  18364. });
  18365. });
  18366. this._setEventListeners(selectElement, null, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"], ["input", "Action"], ["input", "Validate"]], event => event.target.value);
  18367. } else {
  18368. selectElement.addEventListener("input", function (event) {
  18369. storage.setValue(id, {
  18370. value: getValue(true)
  18371. });
  18372. });
  18373. }
  18374. if (this.data.combo) {
  18375. this._setTextStyle(selectElement);
  18376. } else {}
  18377. this._setBackgroundColor(selectElement);
  18378. this._setDefaultPropertiesFromJS(selectElement);
  18379. this.container.append(selectElement);
  18380. return this.container;
  18381. }
  18382. }
  18383. class PopupAnnotationElement extends AnnotationElement {
  18384. constructor(parameters) {
  18385. const {
  18386. data,
  18387. elements
  18388. } = parameters;
  18389. super(parameters, {
  18390. isRenderable: AnnotationElement._hasPopupData(data)
  18391. });
  18392. this.elements = elements;
  18393. this.popup = null;
  18394. }
  18395. render() {
  18396. this.container.classList.add("popupAnnotation");
  18397. const popup = this.popup = new PopupElement({
  18398. container: this.container,
  18399. color: this.data.color,
  18400. titleObj: this.data.titleObj,
  18401. modificationDate: this.data.modificationDate,
  18402. contentsObj: this.data.contentsObj,
  18403. richText: this.data.richText,
  18404. rect: this.data.rect,
  18405. parentRect: this.data.parentRect || null,
  18406. parent: this.parent,
  18407. elements: this.elements,
  18408. open: this.data.open
  18409. });
  18410. const elementIds = [];
  18411. for (const element of this.elements) {
  18412. element.popup = popup;
  18413. elementIds.push(element.data.id);
  18414. element.addHighlightArea();
  18415. }
  18416. this.container.setAttribute("aria-controls", elementIds.map(id => `${AnnotationPrefix}${id}`).join(","));
  18417. return this.container;
  18418. }
  18419. }
  18420. class PopupElement {
  18421. #boundKeyDown = this.#keyDown.bind(this);
  18422. #boundHide = this.#hide.bind(this);
  18423. #boundShow = this.#show.bind(this);
  18424. #boundToggle = this.#toggle.bind(this);
  18425. #color = null;
  18426. #container = null;
  18427. #contentsObj = null;
  18428. #dateObj = null;
  18429. #elements = null;
  18430. #parent = null;
  18431. #parentRect = null;
  18432. #pinned = false;
  18433. #popup = null;
  18434. #position = null;
  18435. #rect = null;
  18436. #richText = null;
  18437. #titleObj = null;
  18438. #updates = null;
  18439. #wasVisible = false;
  18440. constructor({
  18441. container,
  18442. color,
  18443. elements,
  18444. titleObj,
  18445. modificationDate,
  18446. contentsObj,
  18447. richText,
  18448. parent,
  18449. rect,
  18450. parentRect,
  18451. open
  18452. }) {
  18453. this.#container = container;
  18454. this.#titleObj = titleObj;
  18455. this.#contentsObj = contentsObj;
  18456. this.#richText = richText;
  18457. this.#parent = parent;
  18458. this.#color = color;
  18459. this.#rect = rect;
  18460. this.#parentRect = parentRect;
  18461. this.#elements = elements;
  18462. this.#dateObj = PDFDateString.toDateObject(modificationDate);
  18463. this.trigger = elements.flatMap(e => e.getElementsToTriggerPopup());
  18464. for (const element of this.trigger) {
  18465. element.addEventListener("click", this.#boundToggle);
  18466. element.addEventListener("mouseenter", this.#boundShow);
  18467. element.addEventListener("mouseleave", this.#boundHide);
  18468. element.classList.add("popupTriggerArea");
  18469. }
  18470. for (const element of elements) {
  18471. element.container?.addEventListener("keydown", this.#boundKeyDown);
  18472. }
  18473. this.#container.hidden = true;
  18474. if (open) {
  18475. this.#toggle();
  18476. }
  18477. }
  18478. render() {
  18479. if (this.#popup) {
  18480. return;
  18481. }
  18482. const popup = this.#popup = document.createElement("div");
  18483. popup.className = "popup";
  18484. if (this.#color) {
  18485. const baseColor = popup.style.outlineColor = Util.makeHexColor(...this.#color);
  18486. if (CSS.supports("background-color", "color-mix(in srgb, red 30%, white)")) {
  18487. popup.style.backgroundColor = `color-mix(in srgb, ${baseColor} 30%, white)`;
  18488. } else {
  18489. const BACKGROUND_ENLIGHT = 0.7;
  18490. popup.style.backgroundColor = Util.makeHexColor(...this.#color.map(c => Math.floor(BACKGROUND_ENLIGHT * (255 - c) + c)));
  18491. }
  18492. }
  18493. const header = document.createElement("span");
  18494. header.className = "header";
  18495. const title = document.createElement("h1");
  18496. header.append(title);
  18497. ({
  18498. dir: title.dir,
  18499. str: title.textContent
  18500. } = this.#titleObj);
  18501. popup.append(header);
  18502. if (this.#dateObj) {
  18503. const modificationDate = document.createElement("span");
  18504. modificationDate.classList.add("popupDate");
  18505. modificationDate.setAttribute("data-l10n-id", "pdfjs-annotation-date-time-string");
  18506. modificationDate.setAttribute("data-l10n-args", JSON.stringify({
  18507. dateObj: this.#dateObj.valueOf()
  18508. }));
  18509. header.append(modificationDate);
  18510. }
  18511. const html = this.#html;
  18512. if (html) {
  18513. XfaLayer.render({
  18514. xfaHtml: html,
  18515. intent: "richText",
  18516. div: popup
  18517. });
  18518. popup.lastChild.classList.add("richText", "popupContent");
  18519. } else {
  18520. const contents = this._formatContents(this.#contentsObj);
  18521. popup.append(contents);
  18522. }
  18523. this.#container.append(popup);
  18524. }
  18525. get #html() {
  18526. const richText = this.#richText;
  18527. const contentsObj = this.#contentsObj;
  18528. if (richText?.str && (!contentsObj?.str || contentsObj.str === richText.str)) {
  18529. return this.#richText.html || null;
  18530. }
  18531. return null;
  18532. }
  18533. get #fontSize() {
  18534. return this.#html?.attributes?.style?.fontSize || 0;
  18535. }
  18536. get #fontColor() {
  18537. return this.#html?.attributes?.style?.color || null;
  18538. }
  18539. #makePopupContent(text) {
  18540. const popupLines = [];
  18541. const popupContent = {
  18542. str: text,
  18543. html: {
  18544. name: "div",
  18545. attributes: {
  18546. dir: "auto"
  18547. },
  18548. children: [{
  18549. name: "p",
  18550. children: popupLines
  18551. }]
  18552. }
  18553. };
  18554. const lineAttributes = {
  18555. style: {
  18556. color: this.#fontColor,
  18557. fontSize: this.#fontSize ? `calc(${this.#fontSize}px * var(--scale-factor))` : ""
  18558. }
  18559. };
  18560. for (const line of text.split("\n")) {
  18561. popupLines.push({
  18562. name: "span",
  18563. value: line,
  18564. attributes: lineAttributes
  18565. });
  18566. }
  18567. return popupContent;
  18568. }
  18569. _formatContents({
  18570. str,
  18571. dir
  18572. }) {
  18573. const p = document.createElement("p");
  18574. p.classList.add("popupContent");
  18575. p.dir = dir;
  18576. const lines = str.split(/(?:\r\n?|\n)/);
  18577. for (let i = 0, ii = lines.length; i < ii; ++i) {
  18578. const line = lines[i];
  18579. p.append(document.createTextNode(line));
  18580. if (i < ii - 1) {
  18581. p.append(document.createElement("br"));
  18582. }
  18583. }
  18584. return p;
  18585. }
  18586. #keyDown(event) {
  18587. if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) {
  18588. return;
  18589. }
  18590. if (event.key === "Enter" || event.key === "Escape" && this.#pinned) {
  18591. this.#toggle();
  18592. }
  18593. }
  18594. updateEdited({
  18595. rect,
  18596. popupContent
  18597. }) {
  18598. this.#updates ||= {
  18599. contentsObj: this.#contentsObj,
  18600. richText: this.#richText
  18601. };
  18602. if (rect) {
  18603. this.#position = null;
  18604. }
  18605. if (popupContent) {
  18606. this.#richText = this.#makePopupContent(popupContent);
  18607. this.#contentsObj = null;
  18608. }
  18609. this.#popup?.remove();
  18610. this.#popup = null;
  18611. }
  18612. resetEdited() {
  18613. if (!this.#updates) {
  18614. return;
  18615. }
  18616. ({
  18617. contentsObj: this.#contentsObj,
  18618. richText: this.#richText
  18619. } = this.#updates);
  18620. this.#updates = null;
  18621. this.#popup?.remove();
  18622. this.#popup = null;
  18623. this.#position = null;
  18624. }
  18625. #setPosition() {
  18626. if (this.#position !== null) {
  18627. return;
  18628. }
  18629. const {
  18630. page: {
  18631. view
  18632. },
  18633. viewport: {
  18634. rawDims: {
  18635. pageWidth,
  18636. pageHeight,
  18637. pageX,
  18638. pageY
  18639. }
  18640. }
  18641. } = this.#parent;
  18642. let useParentRect = !!this.#parentRect;
  18643. let rect = useParentRect ? this.#parentRect : this.#rect;
  18644. for (const element of this.#elements) {
  18645. if (!rect || Util.intersect(element.data.rect, rect) !== null) {
  18646. rect = element.data.rect;
  18647. useParentRect = true;
  18648. break;
  18649. }
  18650. }
  18651. const normalizedRect = Util.normalizeRect([rect[0], view[3] - rect[1] + view[1], rect[2], view[3] - rect[3] + view[1]]);
  18652. const HORIZONTAL_SPACE_AFTER_ANNOTATION = 5;
  18653. const parentWidth = useParentRect ? rect[2] - rect[0] + HORIZONTAL_SPACE_AFTER_ANNOTATION : 0;
  18654. const popupLeft = normalizedRect[0] + parentWidth;
  18655. const popupTop = normalizedRect[1];
  18656. this.#position = [100 * (popupLeft - pageX) / pageWidth, 100 * (popupTop - pageY) / pageHeight];
  18657. const {
  18658. style
  18659. } = this.#container;
  18660. style.left = `${this.#position[0]}%`;
  18661. style.top = `${this.#position[1]}%`;
  18662. }
  18663. #toggle() {
  18664. this.#pinned = !this.#pinned;
  18665. if (this.#pinned) {
  18666. this.#show();
  18667. this.#container.addEventListener("click", this.#boundToggle);
  18668. this.#container.addEventListener("keydown", this.#boundKeyDown);
  18669. } else {
  18670. this.#hide();
  18671. this.#container.removeEventListener("click", this.#boundToggle);
  18672. this.#container.removeEventListener("keydown", this.#boundKeyDown);
  18673. }
  18674. }
  18675. #show() {
  18676. if (!this.#popup) {
  18677. this.render();
  18678. }
  18679. if (!this.isVisible) {
  18680. this.#setPosition();
  18681. this.#container.hidden = false;
  18682. this.#container.style.zIndex = parseInt(this.#container.style.zIndex) + 1000;
  18683. } else if (this.#pinned) {
  18684. this.#container.classList.add("focused");
  18685. }
  18686. }
  18687. #hide() {
  18688. this.#container.classList.remove("focused");
  18689. if (this.#pinned || !this.isVisible) {
  18690. return;
  18691. }
  18692. this.#container.hidden = true;
  18693. this.#container.style.zIndex = parseInt(this.#container.style.zIndex) - 1000;
  18694. }
  18695. forceHide() {
  18696. this.#wasVisible = this.isVisible;
  18697. if (!this.#wasVisible) {
  18698. return;
  18699. }
  18700. this.#container.hidden = true;
  18701. }
  18702. maybeShow() {
  18703. if (!this.#wasVisible) {
  18704. return;
  18705. }
  18706. if (!this.#popup) {
  18707. this.#show();
  18708. }
  18709. this.#wasVisible = false;
  18710. this.#container.hidden = false;
  18711. }
  18712. get isVisible() {
  18713. return this.#container.hidden === false;
  18714. }
  18715. }
  18716. class FreeTextAnnotationElement extends AnnotationElement {
  18717. constructor(parameters) {
  18718. super(parameters, {
  18719. isRenderable: true,
  18720. ignoreBorder: true
  18721. });
  18722. this.textContent = parameters.data.textContent;
  18723. this.textPosition = parameters.data.textPosition;
  18724. this.annotationEditorType = AnnotationEditorType.FREETEXT;
  18725. }
  18726. render() {
  18727. this.container.classList.add("freeTextAnnotation");
  18728. if (this.textContent) {
  18729. const content = document.createElement("div");
  18730. content.classList.add("annotationTextContent");
  18731. content.setAttribute("role", "comment");
  18732. for (const line of this.textContent) {
  18733. const lineSpan = document.createElement("span");
  18734. lineSpan.textContent = line;
  18735. content.append(lineSpan);
  18736. }
  18737. this.container.append(content);
  18738. }
  18739. if (!this.data.popupRef && this.hasPopupData) {
  18740. this._createPopup();
  18741. }
  18742. this._editOnDoubleClick();
  18743. return this.container;
  18744. }
  18745. }
  18746. class LineAnnotationElement extends AnnotationElement {
  18747. #line = null;
  18748. constructor(parameters) {
  18749. super(parameters, {
  18750. isRenderable: true,
  18751. ignoreBorder: true
  18752. });
  18753. }
  18754. render() {
  18755. this.container.classList.add("lineAnnotation");
  18756. const data = this.data;
  18757. const {
  18758. width,
  18759. height
  18760. } = getRectDims(data.rect);
  18761. const svg = this.svgFactory.create(width, height, true);
  18762. const line = this.#line = this.svgFactory.createElement("svg:line");
  18763. line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
  18764. line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
  18765. line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
  18766. line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
  18767. line.setAttribute("stroke-width", data.borderStyle.width || 1);
  18768. line.setAttribute("stroke", "transparent");
  18769. line.setAttribute("fill", "transparent");
  18770. svg.append(line);
  18771. this.container.append(svg);
  18772. if (!data.popupRef && this.hasPopupData) {
  18773. this._createPopup();
  18774. }
  18775. return this.container;
  18776. }
  18777. getElementsToTriggerPopup() {
  18778. return this.#line;
  18779. }
  18780. addHighlightArea() {
  18781. this.container.classList.add("highlightArea");
  18782. }
  18783. }
  18784. class SquareAnnotationElement extends AnnotationElement {
  18785. #square = null;
  18786. constructor(parameters) {
  18787. super(parameters, {
  18788. isRenderable: true,
  18789. ignoreBorder: true
  18790. });
  18791. }
  18792. render() {
  18793. this.container.classList.add("squareAnnotation");
  18794. const data = this.data;
  18795. const {
  18796. width,
  18797. height
  18798. } = getRectDims(data.rect);
  18799. const svg = this.svgFactory.create(width, height, true);
  18800. const borderWidth = data.borderStyle.width;
  18801. const square = this.#square = this.svgFactory.createElement("svg:rect");
  18802. square.setAttribute("x", borderWidth / 2);
  18803. square.setAttribute("y", borderWidth / 2);
  18804. square.setAttribute("width", width - borderWidth);
  18805. square.setAttribute("height", height - borderWidth);
  18806. square.setAttribute("stroke-width", borderWidth || 1);
  18807. square.setAttribute("stroke", "transparent");
  18808. square.setAttribute("fill", "transparent");
  18809. svg.append(square);
  18810. this.container.append(svg);
  18811. if (!data.popupRef && this.hasPopupData) {
  18812. this._createPopup();
  18813. }
  18814. return this.container;
  18815. }
  18816. getElementsToTriggerPopup() {
  18817. return this.#square;
  18818. }
  18819. addHighlightArea() {
  18820. this.container.classList.add("highlightArea");
  18821. }
  18822. }
  18823. class CircleAnnotationElement extends AnnotationElement {
  18824. #circle = null;
  18825. constructor(parameters) {
  18826. super(parameters, {
  18827. isRenderable: true,
  18828. ignoreBorder: true
  18829. });
  18830. }
  18831. render() {
  18832. this.container.classList.add("circleAnnotation");
  18833. const data = this.data;
  18834. const {
  18835. width,
  18836. height
  18837. } = getRectDims(data.rect);
  18838. const svg = this.svgFactory.create(width, height, true);
  18839. const borderWidth = data.borderStyle.width;
  18840. const circle = this.#circle = this.svgFactory.createElement("svg:ellipse");
  18841. circle.setAttribute("cx", width / 2);
  18842. circle.setAttribute("cy", height / 2);
  18843. circle.setAttribute("rx", width / 2 - borderWidth / 2);
  18844. circle.setAttribute("ry", height / 2 - borderWidth / 2);
  18845. circle.setAttribute("stroke-width", borderWidth || 1);
  18846. circle.setAttribute("stroke", "transparent");
  18847. circle.setAttribute("fill", "transparent");
  18848. svg.append(circle);
  18849. this.container.append(svg);
  18850. if (!data.popupRef && this.hasPopupData) {
  18851. this._createPopup();
  18852. }
  18853. return this.container;
  18854. }
  18855. getElementsToTriggerPopup() {
  18856. return this.#circle;
  18857. }
  18858. addHighlightArea() {
  18859. this.container.classList.add("highlightArea");
  18860. }
  18861. }
  18862. class PolylineAnnotationElement extends AnnotationElement {
  18863. #polyline = null;
  18864. constructor(parameters) {
  18865. super(parameters, {
  18866. isRenderable: true,
  18867. ignoreBorder: true
  18868. });
  18869. this.containerClassName = "polylineAnnotation";
  18870. this.svgElementName = "svg:polyline";
  18871. }
  18872. render() {
  18873. this.container.classList.add(this.containerClassName);
  18874. const {
  18875. data: {
  18876. rect,
  18877. vertices,
  18878. borderStyle,
  18879. popupRef
  18880. }
  18881. } = this;
  18882. if (!vertices) {
  18883. return this.container;
  18884. }
  18885. const {
  18886. width,
  18887. height
  18888. } = getRectDims(rect);
  18889. const svg = this.svgFactory.create(width, height, true);
  18890. let points = [];
  18891. for (let i = 0, ii = vertices.length; i < ii; i += 2) {
  18892. const x = vertices[i] - rect[0];
  18893. const y = rect[3] - vertices[i + 1];
  18894. points.push(`${x},${y}`);
  18895. }
  18896. points = points.join(" ");
  18897. const polyline = this.#polyline = this.svgFactory.createElement(this.svgElementName);
  18898. polyline.setAttribute("points", points);
  18899. polyline.setAttribute("stroke-width", borderStyle.width || 1);
  18900. polyline.setAttribute("stroke", "transparent");
  18901. polyline.setAttribute("fill", "transparent");
  18902. svg.append(polyline);
  18903. this.container.append(svg);
  18904. if (!popupRef && this.hasPopupData) {
  18905. this._createPopup();
  18906. }
  18907. return this.container;
  18908. }
  18909. getElementsToTriggerPopup() {
  18910. return this.#polyline;
  18911. }
  18912. addHighlightArea() {
  18913. this.container.classList.add("highlightArea");
  18914. }
  18915. }
  18916. class PolygonAnnotationElement extends PolylineAnnotationElement {
  18917. constructor(parameters) {
  18918. super(parameters);
  18919. this.containerClassName = "polygonAnnotation";
  18920. this.svgElementName = "svg:polygon";
  18921. }
  18922. }
  18923. class CaretAnnotationElement extends AnnotationElement {
  18924. constructor(parameters) {
  18925. super(parameters, {
  18926. isRenderable: true,
  18927. ignoreBorder: true
  18928. });
  18929. }
  18930. render() {
  18931. this.container.classList.add("caretAnnotation");
  18932. if (!this.data.popupRef && this.hasPopupData) {
  18933. this._createPopup();
  18934. }
  18935. return this.container;
  18936. }
  18937. }
  18938. class InkAnnotationElement extends AnnotationElement {
  18939. #polylines = [];
  18940. constructor(parameters) {
  18941. super(parameters, {
  18942. isRenderable: true,
  18943. ignoreBorder: true
  18944. });
  18945. this.containerClassName = "inkAnnotation";
  18946. this.svgElementName = "svg:polyline";
  18947. this.annotationEditorType = this.data.it === "InkHighlight" ? AnnotationEditorType.HIGHLIGHT : AnnotationEditorType.INK;
  18948. }
  18949. render() {
  18950. this.container.classList.add(this.containerClassName);
  18951. const {
  18952. data: {
  18953. rect,
  18954. inkLists,
  18955. borderStyle,
  18956. popupRef
  18957. }
  18958. } = this;
  18959. const {
  18960. width,
  18961. height
  18962. } = getRectDims(rect);
  18963. const svg = this.svgFactory.create(width, height, true);
  18964. for (const inkList of inkLists) {
  18965. let points = [];
  18966. for (let i = 0, ii = inkList.length; i < ii; i += 2) {
  18967. const x = inkList[i] - rect[0];
  18968. const y = rect[3] - inkList[i + 1];
  18969. points.push(`${x},${y}`);
  18970. }
  18971. points = points.join(" ");
  18972. const polyline = this.svgFactory.createElement(this.svgElementName);
  18973. this.#polylines.push(polyline);
  18974. polyline.setAttribute("points", points);
  18975. polyline.setAttribute("stroke-width", borderStyle.width || 1);
  18976. polyline.setAttribute("stroke", "transparent");
  18977. polyline.setAttribute("fill", "transparent");
  18978. if (!popupRef && this.hasPopupData) {
  18979. this._createPopup();
  18980. }
  18981. svg.append(polyline);
  18982. }
  18983. this.container.append(svg);
  18984. this._editOnDoubleClick();
  18985. return this.container;
  18986. }
  18987. getElementsToTriggerPopup() {
  18988. return this.#polylines;
  18989. }
  18990. addHighlightArea() {
  18991. this.container.classList.add("highlightArea");
  18992. }
  18993. }
  18994. class HighlightAnnotationElement extends AnnotationElement {
  18995. constructor(parameters) {
  18996. super(parameters, {
  18997. isRenderable: true,
  18998. ignoreBorder: true,
  18999. createQuadrilaterals: true
  19000. });
  19001. this.annotationEditorType = AnnotationEditorType.HIGHLIGHT;
  19002. }
  19003. render() {
  19004. if (!this.data.popupRef && this.hasPopupData) {
  19005. this._createPopup();
  19006. }
  19007. this.container.classList.add("highlightAnnotation");
  19008. this._editOnDoubleClick();
  19009. return this.container;
  19010. }
  19011. }
  19012. class UnderlineAnnotationElement extends AnnotationElement {
  19013. constructor(parameters) {
  19014. super(parameters, {
  19015. isRenderable: true,
  19016. ignoreBorder: true,
  19017. createQuadrilaterals: true
  19018. });
  19019. }
  19020. render() {
  19021. if (!this.data.popupRef && this.hasPopupData) {
  19022. this._createPopup();
  19023. }
  19024. this.container.classList.add("underlineAnnotation");
  19025. return this.container;
  19026. }
  19027. }
  19028. class SquigglyAnnotationElement extends AnnotationElement {
  19029. constructor(parameters) {
  19030. super(parameters, {
  19031. isRenderable: true,
  19032. ignoreBorder: true,
  19033. createQuadrilaterals: true
  19034. });
  19035. }
  19036. render() {
  19037. if (!this.data.popupRef && this.hasPopupData) {
  19038. this._createPopup();
  19039. }
  19040. this.container.classList.add("squigglyAnnotation");
  19041. return this.container;
  19042. }
  19043. }
  19044. class StrikeOutAnnotationElement extends AnnotationElement {
  19045. constructor(parameters) {
  19046. super(parameters, {
  19047. isRenderable: true,
  19048. ignoreBorder: true,
  19049. createQuadrilaterals: true
  19050. });
  19051. }
  19052. render() {
  19053. if (!this.data.popupRef && this.hasPopupData) {
  19054. this._createPopup();
  19055. }
  19056. this.container.classList.add("strikeoutAnnotation");
  19057. return this.container;
  19058. }
  19059. }
  19060. class StampAnnotationElement extends AnnotationElement {
  19061. constructor(parameters) {
  19062. super(parameters, {
  19063. isRenderable: true,
  19064. ignoreBorder: true
  19065. });
  19066. this.annotationEditorType = AnnotationEditorType.STAMP;
  19067. }
  19068. render() {
  19069. this.container.classList.add("stampAnnotation");
  19070. this.container.setAttribute("role", "img");
  19071. if (!this.data.popupRef && this.hasPopupData) {
  19072. this._createPopup();
  19073. }
  19074. this._editOnDoubleClick();
  19075. return this.container;
  19076. }
  19077. }
  19078. class FileAttachmentAnnotationElement extends AnnotationElement {
  19079. #trigger = null;
  19080. constructor(parameters) {
  19081. super(parameters, {
  19082. isRenderable: true
  19083. });
  19084. const {
  19085. file
  19086. } = this.data;
  19087. this.filename = file.filename;
  19088. this.content = file.content;
  19089. this.linkService.eventBus?.dispatch("fileattachmentannotation", {
  19090. source: this,
  19091. ...file
  19092. });
  19093. }
  19094. render() {
  19095. this.container.classList.add("fileAttachmentAnnotation");
  19096. const {
  19097. container,
  19098. data
  19099. } = this;
  19100. let trigger;
  19101. if (data.hasAppearance || data.fillAlpha === 0) {
  19102. trigger = document.createElement("div");
  19103. } else {
  19104. trigger = document.createElement("img");
  19105. trigger.src = `${this.imageResourcesPath}annotation-${/paperclip/i.test(data.name) ? "paperclip" : "pushpin"}.svg`;
  19106. if (data.fillAlpha && data.fillAlpha < 1) {
  19107. trigger.style = `filter: opacity(${Math.round(data.fillAlpha * 100)}%);`;
  19108. }
  19109. }
  19110. trigger.addEventListener("dblclick", this.#download.bind(this));
  19111. this.#trigger = trigger;
  19112. const {
  19113. isMac
  19114. } = util_FeatureTest.platform;
  19115. container.addEventListener("keydown", evt => {
  19116. if (evt.key === "Enter" && (isMac ? evt.metaKey : evt.ctrlKey)) {
  19117. this.#download();
  19118. }
  19119. });
  19120. if (!data.popupRef && this.hasPopupData) {
  19121. this._createPopup();
  19122. } else {
  19123. trigger.classList.add("popupTriggerArea");
  19124. }
  19125. container.append(trigger);
  19126. return container;
  19127. }
  19128. getElementsToTriggerPopup() {
  19129. return this.#trigger;
  19130. }
  19131. addHighlightArea() {
  19132. this.container.classList.add("highlightArea");
  19133. }
  19134. #download() {
  19135. this.downloadManager?.openOrDownloadData(this.content, this.filename);
  19136. }
  19137. }
  19138. class AnnotationLayer {
  19139. #accessibilityManager = null;
  19140. #annotationCanvasMap = null;
  19141. #editableAnnotations = new Map();
  19142. #structTreeLayer = null;
  19143. constructor({
  19144. div,
  19145. accessibilityManager,
  19146. annotationCanvasMap,
  19147. annotationEditorUIManager,
  19148. page,
  19149. viewport,
  19150. structTreeLayer
  19151. }) {
  19152. this.div = div;
  19153. this.#accessibilityManager = accessibilityManager;
  19154. this.#annotationCanvasMap = annotationCanvasMap;
  19155. this.#structTreeLayer = structTreeLayer || null;
  19156. this.page = page;
  19157. this.viewport = viewport;
  19158. this.zIndex = 0;
  19159. this._annotationEditorUIManager = annotationEditorUIManager;
  19160. }
  19161. hasEditableAnnotations() {
  19162. return this.#editableAnnotations.size > 0;
  19163. }
  19164. async #appendElement(element, id) {
  19165. const contentElement = element.firstChild || element;
  19166. const annotationId = contentElement.id = `${AnnotationPrefix}${id}`;
  19167. const ariaAttributes = await this.#structTreeLayer?.getAriaAttributes(annotationId);
  19168. if (ariaAttributes) {
  19169. for (const [key, value] of ariaAttributes) {
  19170. contentElement.setAttribute(key, value);
  19171. }
  19172. }
  19173. this.div.append(element);
  19174. this.#accessibilityManager?.moveElementInDOM(this.div, element, contentElement, false);
  19175. }
  19176. async render(params) {
  19177. const {
  19178. annotations
  19179. } = params;
  19180. const layer = this.div;
  19181. setLayerDimensions(layer, this.viewport);
  19182. const popupToElements = new Map();
  19183. const elementParams = {
  19184. data: null,
  19185. layer,
  19186. linkService: params.linkService,
  19187. downloadManager: params.downloadManager,
  19188. imageResourcesPath: params.imageResourcesPath || "",
  19189. renderForms: params.renderForms !== false,
  19190. svgFactory: new DOMSVGFactory(),
  19191. annotationStorage: params.annotationStorage || new AnnotationStorage(),
  19192. enableScripting: params.enableScripting === true,
  19193. hasJSActions: params.hasJSActions,
  19194. fieldObjects: params.fieldObjects,
  19195. parent: this,
  19196. elements: null
  19197. };
  19198. for (const data of annotations) {
  19199. if (data.noHTML) {
  19200. continue;
  19201. }
  19202. const isPopupAnnotation = data.annotationType === AnnotationType.POPUP;
  19203. if (!isPopupAnnotation) {
  19204. const {
  19205. width,
  19206. height
  19207. } = getRectDims(data.rect);
  19208. if (width <= 0 || height <= 0) {
  19209. continue;
  19210. }
  19211. } else {
  19212. const elements = popupToElements.get(data.id);
  19213. if (!elements) {
  19214. continue;
  19215. }
  19216. elementParams.elements = elements;
  19217. }
  19218. elementParams.data = data;
  19219. const element = AnnotationElementFactory.create(elementParams);
  19220. if (!element.isRenderable) {
  19221. continue;
  19222. }
  19223. if (!isPopupAnnotation && data.popupRef) {
  19224. const elements = popupToElements.get(data.popupRef);
  19225. if (!elements) {
  19226. popupToElements.set(data.popupRef, [element]);
  19227. } else {
  19228. elements.push(element);
  19229. }
  19230. }
  19231. const rendered = element.render();
  19232. if (data.hidden) {
  19233. rendered.style.visibility = "hidden";
  19234. }
  19235. await this.#appendElement(rendered, data.id);
  19236. if (element._isEditable) {
  19237. this.#editableAnnotations.set(element.data.id, element);
  19238. this._annotationEditorUIManager?.renderAnnotationElement(element);
  19239. }
  19240. }
  19241. this.#setAnnotationCanvasMap();
  19242. }
  19243. update({
  19244. viewport
  19245. }) {
  19246. const layer = this.div;
  19247. this.viewport = viewport;
  19248. setLayerDimensions(layer, {
  19249. rotation: viewport.rotation
  19250. });
  19251. this.#setAnnotationCanvasMap();
  19252. layer.hidden = false;
  19253. }
  19254. #setAnnotationCanvasMap() {
  19255. if (!this.#annotationCanvasMap) {
  19256. return;
  19257. }
  19258. const layer = this.div;
  19259. for (const [id, canvas] of this.#annotationCanvasMap) {
  19260. const element = layer.querySelector(`[data-annotation-id="${id}"]`);
  19261. if (!element) {
  19262. continue;
  19263. }
  19264. canvas.className = "annotationContent";
  19265. const {
  19266. firstChild
  19267. } = element;
  19268. if (!firstChild) {
  19269. element.append(canvas);
  19270. } else if (firstChild.nodeName === "CANVAS") {
  19271. firstChild.replaceWith(canvas);
  19272. } else if (!firstChild.classList.contains("annotationContent")) {
  19273. firstChild.before(canvas);
  19274. } else {
  19275. firstChild.after(canvas);
  19276. }
  19277. }
  19278. this.#annotationCanvasMap.clear();
  19279. }
  19280. getEditableAnnotations() {
  19281. return Array.from(this.#editableAnnotations.values());
  19282. }
  19283. getEditableAnnotation(id) {
  19284. return this.#editableAnnotations.get(id);
  19285. }
  19286. }
  19287. ;// ./src/display/editor/freetext.js
  19288. const EOL_PATTERN = /\r\n?|\n/g;
  19289. class FreeTextEditor extends AnnotationEditor {
  19290. #color;
  19291. #content = "";
  19292. #editorDivId = `${this.id}-editor`;
  19293. #editModeAC = null;
  19294. #fontSize;
  19295. static _freeTextDefaultContent = "";
  19296. static _internalPadding = 0;
  19297. static _defaultColor = null;
  19298. static _defaultFontSize = 10;
  19299. static get _keyboardManager() {
  19300. const proto = FreeTextEditor.prototype;
  19301. const arrowChecker = self => self.isEmpty();
  19302. const small = AnnotationEditorUIManager.TRANSLATE_SMALL;
  19303. const big = AnnotationEditorUIManager.TRANSLATE_BIG;
  19304. return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+s", "mac+meta+s", "ctrl+p", "mac+meta+p"], proto.commitOrRemove, {
  19305. bubbles: true
  19306. }], [["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], proto.commitOrRemove], [["ArrowLeft", "mac+ArrowLeft"], proto._translateEmpty, {
  19307. args: [-small, 0],
  19308. checker: arrowChecker
  19309. }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto._translateEmpty, {
  19310. args: [-big, 0],
  19311. checker: arrowChecker
  19312. }], [["ArrowRight", "mac+ArrowRight"], proto._translateEmpty, {
  19313. args: [small, 0],
  19314. checker: arrowChecker
  19315. }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto._translateEmpty, {
  19316. args: [big, 0],
  19317. checker: arrowChecker
  19318. }], [["ArrowUp", "mac+ArrowUp"], proto._translateEmpty, {
  19319. args: [0, -small],
  19320. checker: arrowChecker
  19321. }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto._translateEmpty, {
  19322. args: [0, -big],
  19323. checker: arrowChecker
  19324. }], [["ArrowDown", "mac+ArrowDown"], proto._translateEmpty, {
  19325. args: [0, small],
  19326. checker: arrowChecker
  19327. }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto._translateEmpty, {
  19328. args: [0, big],
  19329. checker: arrowChecker
  19330. }]]));
  19331. }
  19332. static _type = "freetext";
  19333. static _editorType = AnnotationEditorType.FREETEXT;
  19334. constructor(params) {
  19335. super({
  19336. ...params,
  19337. name: "freeTextEditor"
  19338. });
  19339. this.#color = params.color || FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor;
  19340. this.#fontSize = params.fontSize || FreeTextEditor._defaultFontSize;
  19341. }
  19342. static initialize(l10n, uiManager) {
  19343. AnnotationEditor.initialize(l10n, uiManager, {
  19344. strings: ["pdfjs-free-text-default-content"]
  19345. });
  19346. const style = getComputedStyle(document.documentElement);
  19347. this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding"));
  19348. }
  19349. static updateDefaultParams(type, value) {
  19350. switch (type) {
  19351. case AnnotationEditorParamsType.FREETEXT_SIZE:
  19352. FreeTextEditor._defaultFontSize = value;
  19353. break;
  19354. case AnnotationEditorParamsType.FREETEXT_COLOR:
  19355. FreeTextEditor._defaultColor = value;
  19356. break;
  19357. }
  19358. }
  19359. updateParams(type, value) {
  19360. switch (type) {
  19361. case AnnotationEditorParamsType.FREETEXT_SIZE:
  19362. this.#updateFontSize(value);
  19363. break;
  19364. case AnnotationEditorParamsType.FREETEXT_COLOR:
  19365. this.#updateColor(value);
  19366. break;
  19367. }
  19368. }
  19369. static get defaultPropertiesToUpdate() {
  19370. return [[AnnotationEditorParamsType.FREETEXT_SIZE, FreeTextEditor._defaultFontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor]];
  19371. }
  19372. get propertiesToUpdate() {
  19373. return [[AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, this.#color]];
  19374. }
  19375. #updateFontSize(fontSize) {
  19376. const setFontsize = size => {
  19377. this.editorDiv.style.fontSize = `calc(${size}px * var(--scale-factor))`;
  19378. this.translate(0, -(size - this.#fontSize) * this.parentScale);
  19379. this.#fontSize = size;
  19380. this.#setEditorDimensions();
  19381. };
  19382. const savedFontsize = this.#fontSize;
  19383. this.addCommands({
  19384. cmd: setFontsize.bind(this, fontSize),
  19385. undo: setFontsize.bind(this, savedFontsize),
  19386. post: this._uiManager.updateUI.bind(this._uiManager, this),
  19387. mustExec: true,
  19388. type: AnnotationEditorParamsType.FREETEXT_SIZE,
  19389. overwriteIfSameType: true,
  19390. keepUndo: true
  19391. });
  19392. }
  19393. #updateColor(color) {
  19394. const setColor = col => {
  19395. this.#color = this.editorDiv.style.color = col;
  19396. };
  19397. const savedColor = this.#color;
  19398. this.addCommands({
  19399. cmd: setColor.bind(this, color),
  19400. undo: setColor.bind(this, savedColor),
  19401. post: this._uiManager.updateUI.bind(this._uiManager, this),
  19402. mustExec: true,
  19403. type: AnnotationEditorParamsType.FREETEXT_COLOR,
  19404. overwriteIfSameType: true,
  19405. keepUndo: true
  19406. });
  19407. }
  19408. _translateEmpty(x, y) {
  19409. this._uiManager.translateSelectedEditors(x, y, true);
  19410. }
  19411. getInitialTranslation() {
  19412. const scale = this.parentScale;
  19413. return [-FreeTextEditor._internalPadding * scale, -(FreeTextEditor._internalPadding + this.#fontSize) * scale];
  19414. }
  19415. rebuild() {
  19416. if (!this.parent) {
  19417. return;
  19418. }
  19419. super.rebuild();
  19420. if (this.div === null) {
  19421. return;
  19422. }
  19423. if (!this.isAttachedToDOM) {
  19424. this.parent.add(this);
  19425. }
  19426. }
  19427. enableEditMode() {
  19428. if (this.isInEditMode()) {
  19429. return;
  19430. }
  19431. this.parent.setEditingState(false);
  19432. this.parent.updateToolbar(AnnotationEditorType.FREETEXT);
  19433. super.enableEditMode();
  19434. this.overlayDiv.classList.remove("enabled");
  19435. this.editorDiv.contentEditable = true;
  19436. this._isDraggable = false;
  19437. this.div.removeAttribute("aria-activedescendant");
  19438. this.#editModeAC = new AbortController();
  19439. const signal = this._uiManager.combinedSignal(this.#editModeAC);
  19440. this.editorDiv.addEventListener("keydown", this.editorDivKeydown.bind(this), {
  19441. signal
  19442. });
  19443. this.editorDiv.addEventListener("focus", this.editorDivFocus.bind(this), {
  19444. signal
  19445. });
  19446. this.editorDiv.addEventListener("blur", this.editorDivBlur.bind(this), {
  19447. signal
  19448. });
  19449. this.editorDiv.addEventListener("input", this.editorDivInput.bind(this), {
  19450. signal
  19451. });
  19452. this.editorDiv.addEventListener("paste", this.editorDivPaste.bind(this), {
  19453. signal
  19454. });
  19455. }
  19456. disableEditMode() {
  19457. if (!this.isInEditMode()) {
  19458. return;
  19459. }
  19460. this.parent.setEditingState(true);
  19461. super.disableEditMode();
  19462. this.overlayDiv.classList.add("enabled");
  19463. this.editorDiv.contentEditable = false;
  19464. this.div.setAttribute("aria-activedescendant", this.#editorDivId);
  19465. this._isDraggable = true;
  19466. this.#editModeAC?.abort();
  19467. this.#editModeAC = null;
  19468. this.div.focus({
  19469. preventScroll: true
  19470. });
  19471. this.isEditing = false;
  19472. this.parent.div.classList.add("freetextEditing");
  19473. }
  19474. focusin(event) {
  19475. if (!this._focusEventsAllowed) {
  19476. return;
  19477. }
  19478. super.focusin(event);
  19479. if (event.target !== this.editorDiv) {
  19480. this.editorDiv.focus();
  19481. }
  19482. }
  19483. onceAdded() {
  19484. if (this.width) {
  19485. return;
  19486. }
  19487. this.enableEditMode();
  19488. this.editorDiv.focus();
  19489. if (this._initialOptions?.isCentered) {
  19490. this.center();
  19491. }
  19492. this._initialOptions = null;
  19493. }
  19494. isEmpty() {
  19495. return !this.editorDiv || this.editorDiv.innerText.trim() === "";
  19496. }
  19497. remove() {
  19498. this.isEditing = false;
  19499. if (this.parent) {
  19500. this.parent.setEditingState(true);
  19501. this.parent.div.classList.add("freetextEditing");
  19502. }
  19503. super.remove();
  19504. }
  19505. #extractText() {
  19506. const buffer = [];
  19507. this.editorDiv.normalize();
  19508. let prevChild = null;
  19509. for (const child of this.editorDiv.childNodes) {
  19510. if (prevChild?.nodeType === Node.TEXT_NODE && child.nodeName === "BR") {
  19511. continue;
  19512. }
  19513. buffer.push(FreeTextEditor.#getNodeContent(child));
  19514. prevChild = child;
  19515. }
  19516. return buffer.join("\n");
  19517. }
  19518. #setEditorDimensions() {
  19519. const [parentWidth, parentHeight] = this.parentDimensions;
  19520. let rect;
  19521. if (this.isAttachedToDOM) {
  19522. rect = this.div.getBoundingClientRect();
  19523. } else {
  19524. const {
  19525. currentLayer,
  19526. div
  19527. } = this;
  19528. const savedDisplay = div.style.display;
  19529. const savedVisibility = div.classList.contains("hidden");
  19530. div.classList.remove("hidden");
  19531. div.style.display = "hidden";
  19532. currentLayer.div.append(this.div);
  19533. rect = div.getBoundingClientRect();
  19534. div.remove();
  19535. div.style.display = savedDisplay;
  19536. div.classList.toggle("hidden", savedVisibility);
  19537. }
  19538. if (this.rotation % 180 === this.parentRotation % 180) {
  19539. this.width = rect.width / parentWidth;
  19540. this.height = rect.height / parentHeight;
  19541. } else {
  19542. this.width = rect.height / parentWidth;
  19543. this.height = rect.width / parentHeight;
  19544. }
  19545. this.fixAndSetPosition();
  19546. }
  19547. commit() {
  19548. if (!this.isInEditMode()) {
  19549. return;
  19550. }
  19551. super.commit();
  19552. this.disableEditMode();
  19553. const savedText = this.#content;
  19554. const newText = this.#content = this.#extractText().trimEnd();
  19555. if (savedText === newText) {
  19556. return;
  19557. }
  19558. const setText = text => {
  19559. this.#content = text;
  19560. if (!text) {
  19561. this.remove();
  19562. return;
  19563. }
  19564. this.#setContent();
  19565. this._uiManager.rebuild(this);
  19566. this.#setEditorDimensions();
  19567. };
  19568. this.addCommands({
  19569. cmd: () => {
  19570. setText(newText);
  19571. },
  19572. undo: () => {
  19573. setText(savedText);
  19574. },
  19575. mustExec: false
  19576. });
  19577. this.#setEditorDimensions();
  19578. }
  19579. shouldGetKeyboardEvents() {
  19580. return this.isInEditMode();
  19581. }
  19582. enterInEditMode() {
  19583. this.enableEditMode();
  19584. this.editorDiv.focus();
  19585. }
  19586. dblclick(event) {
  19587. this.enterInEditMode();
  19588. }
  19589. keydown(event) {
  19590. if (event.target === this.div && event.key === "Enter") {
  19591. this.enterInEditMode();
  19592. event.preventDefault();
  19593. }
  19594. }
  19595. editorDivKeydown(event) {
  19596. FreeTextEditor._keyboardManager.exec(this, event);
  19597. }
  19598. editorDivFocus(event) {
  19599. this.isEditing = true;
  19600. }
  19601. editorDivBlur(event) {
  19602. this.isEditing = false;
  19603. }
  19604. editorDivInput(event) {
  19605. this.parent.div.classList.toggle("freetextEditing", this.isEmpty());
  19606. }
  19607. disableEditing() {
  19608. this.editorDiv.setAttribute("role", "comment");
  19609. this.editorDiv.removeAttribute("aria-multiline");
  19610. }
  19611. enableEditing() {
  19612. this.editorDiv.setAttribute("role", "textbox");
  19613. this.editorDiv.setAttribute("aria-multiline", true);
  19614. }
  19615. render() {
  19616. if (this.div) {
  19617. return this.div;
  19618. }
  19619. let baseX, baseY;
  19620. if (this.width) {
  19621. baseX = this.x;
  19622. baseY = this.y;
  19623. }
  19624. super.render();
  19625. this.editorDiv = document.createElement("div");
  19626. this.editorDiv.className = "internal";
  19627. this.editorDiv.setAttribute("id", this.#editorDivId);
  19628. this.editorDiv.setAttribute("data-l10n-id", "pdfjs-free-text");
  19629. this.enableEditing();
  19630. AnnotationEditor._l10nPromise.get("pdfjs-free-text-default-content").then(msg => this.editorDiv?.setAttribute("default-content", msg));
  19631. this.editorDiv.contentEditable = true;
  19632. const {
  19633. style
  19634. } = this.editorDiv;
  19635. style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`;
  19636. style.color = this.#color;
  19637. this.div.append(this.editorDiv);
  19638. this.overlayDiv = document.createElement("div");
  19639. this.overlayDiv.classList.add("overlay", "enabled");
  19640. this.div.append(this.overlayDiv);
  19641. bindEvents(this, this.div, ["dblclick", "keydown"]);
  19642. if (this.width) {
  19643. const [parentWidth, parentHeight] = this.parentDimensions;
  19644. if (this.annotationElementId) {
  19645. const {
  19646. position
  19647. } = this._initialData;
  19648. let [tx, ty] = this.getInitialTranslation();
  19649. [tx, ty] = this.pageTranslationToScreen(tx, ty);
  19650. const [pageWidth, pageHeight] = this.pageDimensions;
  19651. const [pageX, pageY] = this.pageTranslation;
  19652. let posX, posY;
  19653. switch (this.rotation) {
  19654. case 0:
  19655. posX = baseX + (position[0] - pageX) / pageWidth;
  19656. posY = baseY + this.height - (position[1] - pageY) / pageHeight;
  19657. break;
  19658. case 90:
  19659. posX = baseX + (position[0] - pageX) / pageWidth;
  19660. posY = baseY - (position[1] - pageY) / pageHeight;
  19661. [tx, ty] = [ty, -tx];
  19662. break;
  19663. case 180:
  19664. posX = baseX - this.width + (position[0] - pageX) / pageWidth;
  19665. posY = baseY - (position[1] - pageY) / pageHeight;
  19666. [tx, ty] = [-tx, -ty];
  19667. break;
  19668. case 270:
  19669. posX = baseX + (position[0] - pageX - this.height * pageHeight) / pageWidth;
  19670. posY = baseY + (position[1] - pageY - this.width * pageWidth) / pageHeight;
  19671. [tx, ty] = [-ty, tx];
  19672. break;
  19673. }
  19674. this.setAt(posX * parentWidth, posY * parentHeight, tx, ty);
  19675. } else {
  19676. this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
  19677. }
  19678. this.#setContent();
  19679. this._isDraggable = true;
  19680. this.editorDiv.contentEditable = false;
  19681. } else {
  19682. this._isDraggable = false;
  19683. this.editorDiv.contentEditable = true;
  19684. }
  19685. return this.div;
  19686. }
  19687. static #getNodeContent(node) {
  19688. return (node.nodeType === Node.TEXT_NODE ? node.nodeValue : node.innerText).replaceAll(EOL_PATTERN, "");
  19689. }
  19690. editorDivPaste(event) {
  19691. const clipboardData = event.clipboardData || window.clipboardData;
  19692. const {
  19693. types
  19694. } = clipboardData;
  19695. if (types.length === 1 && types[0] === "text/plain") {
  19696. return;
  19697. }
  19698. event.preventDefault();
  19699. const paste = FreeTextEditor.#deserializeContent(clipboardData.getData("text") || "").replaceAll(EOL_PATTERN, "\n");
  19700. if (!paste) {
  19701. return;
  19702. }
  19703. const selection = window.getSelection();
  19704. if (!selection.rangeCount) {
  19705. return;
  19706. }
  19707. this.editorDiv.normalize();
  19708. selection.deleteFromDocument();
  19709. const range = selection.getRangeAt(0);
  19710. if (!paste.includes("\n")) {
  19711. range.insertNode(document.createTextNode(paste));
  19712. this.editorDiv.normalize();
  19713. selection.collapseToStart();
  19714. return;
  19715. }
  19716. const {
  19717. startContainer,
  19718. startOffset
  19719. } = range;
  19720. const bufferBefore = [];
  19721. const bufferAfter = [];
  19722. if (startContainer.nodeType === Node.TEXT_NODE) {
  19723. const parent = startContainer.parentElement;
  19724. bufferAfter.push(startContainer.nodeValue.slice(startOffset).replaceAll(EOL_PATTERN, ""));
  19725. if (parent !== this.editorDiv) {
  19726. let buffer = bufferBefore;
  19727. for (const child of this.editorDiv.childNodes) {
  19728. if (child === parent) {
  19729. buffer = bufferAfter;
  19730. continue;
  19731. }
  19732. buffer.push(FreeTextEditor.#getNodeContent(child));
  19733. }
  19734. }
  19735. bufferBefore.push(startContainer.nodeValue.slice(0, startOffset).replaceAll(EOL_PATTERN, ""));
  19736. } else if (startContainer === this.editorDiv) {
  19737. let buffer = bufferBefore;
  19738. let i = 0;
  19739. for (const child of this.editorDiv.childNodes) {
  19740. if (i++ === startOffset) {
  19741. buffer = bufferAfter;
  19742. }
  19743. buffer.push(FreeTextEditor.#getNodeContent(child));
  19744. }
  19745. }
  19746. this.#content = `${bufferBefore.join("\n")}${paste}${bufferAfter.join("\n")}`;
  19747. this.#setContent();
  19748. const newRange = new Range();
  19749. let beforeLength = bufferBefore.reduce((acc, line) => acc + line.length, 0);
  19750. for (const {
  19751. firstChild
  19752. } of this.editorDiv.childNodes) {
  19753. if (firstChild.nodeType === Node.TEXT_NODE) {
  19754. const length = firstChild.nodeValue.length;
  19755. if (beforeLength <= length) {
  19756. newRange.setStart(firstChild, beforeLength);
  19757. newRange.setEnd(firstChild, beforeLength);
  19758. break;
  19759. }
  19760. beforeLength -= length;
  19761. }
  19762. }
  19763. selection.removeAllRanges();
  19764. selection.addRange(newRange);
  19765. }
  19766. #setContent() {
  19767. this.editorDiv.replaceChildren();
  19768. if (!this.#content) {
  19769. return;
  19770. }
  19771. for (const line of this.#content.split("\n")) {
  19772. const div = document.createElement("div");
  19773. div.append(line ? document.createTextNode(line) : document.createElement("br"));
  19774. this.editorDiv.append(div);
  19775. }
  19776. }
  19777. #serializeContent() {
  19778. return this.#content.replaceAll("\xa0", " ");
  19779. }
  19780. static #deserializeContent(content) {
  19781. return content.replaceAll(" ", "\xa0");
  19782. }
  19783. get contentDiv() {
  19784. return this.editorDiv;
  19785. }
  19786. static async deserialize(data, parent, uiManager) {
  19787. let initialData = null;
  19788. if (data instanceof FreeTextAnnotationElement) {
  19789. const {
  19790. data: {
  19791. defaultAppearanceData: {
  19792. fontSize,
  19793. fontColor
  19794. },
  19795. rect,
  19796. rotation,
  19797. id,
  19798. popupRef
  19799. },
  19800. textContent,
  19801. textPosition,
  19802. parent: {
  19803. page: {
  19804. pageNumber
  19805. }
  19806. }
  19807. } = data;
  19808. if (!textContent || textContent.length === 0) {
  19809. return null;
  19810. }
  19811. initialData = data = {
  19812. annotationType: AnnotationEditorType.FREETEXT,
  19813. color: Array.from(fontColor),
  19814. fontSize,
  19815. value: textContent.join("\n"),
  19816. position: textPosition,
  19817. pageIndex: pageNumber - 1,
  19818. rect: rect.slice(0),
  19819. rotation,
  19820. id,
  19821. deleted: false,
  19822. popupRef
  19823. };
  19824. }
  19825. const editor = await super.deserialize(data, parent, uiManager);
  19826. editor.#fontSize = data.fontSize;
  19827. editor.#color = Util.makeHexColor(...data.color);
  19828. editor.#content = FreeTextEditor.#deserializeContent(data.value);
  19829. editor.annotationElementId = data.id || null;
  19830. editor._initialData = initialData;
  19831. return editor;
  19832. }
  19833. serialize(isForCopying = false) {
  19834. if (this.isEmpty()) {
  19835. return null;
  19836. }
  19837. if (this.deleted) {
  19838. return this.serializeDeleted();
  19839. }
  19840. const padding = FreeTextEditor._internalPadding * this.parentScale;
  19841. const rect = this.getRect(padding, padding);
  19842. const color = AnnotationEditor._colorManager.convert(this.isAttachedToDOM ? getComputedStyle(this.editorDiv).color : this.#color);
  19843. const serialized = {
  19844. annotationType: AnnotationEditorType.FREETEXT,
  19845. color,
  19846. fontSize: this.#fontSize,
  19847. value: this.#serializeContent(),
  19848. pageIndex: this.pageIndex,
  19849. rect,
  19850. rotation: this.rotation,
  19851. structTreeParentId: this._structTreeParentId
  19852. };
  19853. if (isForCopying) {
  19854. return serialized;
  19855. }
  19856. if (this.annotationElementId && !this.#hasElementChanged(serialized)) {
  19857. return null;
  19858. }
  19859. serialized.id = this.annotationElementId;
  19860. return serialized;
  19861. }
  19862. #hasElementChanged(serialized) {
  19863. const {
  19864. value,
  19865. fontSize,
  19866. color,
  19867. pageIndex
  19868. } = this._initialData;
  19869. return this._hasBeenMoved || serialized.value !== value || serialized.fontSize !== fontSize || serialized.color.some((c, i) => c !== color[i]) || serialized.pageIndex !== pageIndex;
  19870. }
  19871. renderAnnotationElement(annotation) {
  19872. const content = super.renderAnnotationElement(annotation);
  19873. if (this.deleted) {
  19874. return content;
  19875. }
  19876. const {
  19877. style
  19878. } = content;
  19879. style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`;
  19880. style.color = this.#color;
  19881. content.replaceChildren();
  19882. for (const line of this.#content.split("\n")) {
  19883. const div = document.createElement("div");
  19884. div.append(line ? document.createTextNode(line) : document.createElement("br"));
  19885. content.append(div);
  19886. }
  19887. const padding = FreeTextEditor._internalPadding * this.parentScale;
  19888. annotation.updateEdited({
  19889. rect: this.getRect(padding, padding),
  19890. popupContent: this.#content
  19891. });
  19892. return content;
  19893. }
  19894. resetAnnotationElement(annotation) {
  19895. super.resetAnnotationElement(annotation);
  19896. annotation.resetEdited();
  19897. }
  19898. }
  19899. ;// ./src/display/editor/outliner.js
  19900. class Outliner {
  19901. #box;
  19902. #verticalEdges = [];
  19903. #intervals = [];
  19904. constructor(boxes, borderWidth = 0, innerMargin = 0, isLTR = true) {
  19905. let minX = Infinity;
  19906. let maxX = -Infinity;
  19907. let minY = Infinity;
  19908. let maxY = -Infinity;
  19909. const NUMBER_OF_DIGITS = 4;
  19910. const EPSILON = 10 ** -NUMBER_OF_DIGITS;
  19911. for (const {
  19912. x,
  19913. y,
  19914. width,
  19915. height
  19916. } of boxes) {
  19917. const x1 = Math.floor((x - borderWidth) / EPSILON) * EPSILON;
  19918. const x2 = Math.ceil((x + width + borderWidth) / EPSILON) * EPSILON;
  19919. const y1 = Math.floor((y - borderWidth) / EPSILON) * EPSILON;
  19920. const y2 = Math.ceil((y + height + borderWidth) / EPSILON) * EPSILON;
  19921. const left = [x1, y1, y2, true];
  19922. const right = [x2, y1, y2, false];
  19923. this.#verticalEdges.push(left, right);
  19924. minX = Math.min(minX, x1);
  19925. maxX = Math.max(maxX, x2);
  19926. minY = Math.min(minY, y1);
  19927. maxY = Math.max(maxY, y2);
  19928. }
  19929. const bboxWidth = maxX - minX + 2 * innerMargin;
  19930. const bboxHeight = maxY - minY + 2 * innerMargin;
  19931. const shiftedMinX = minX - innerMargin;
  19932. const shiftedMinY = minY - innerMargin;
  19933. const lastEdge = this.#verticalEdges.at(isLTR ? -1 : -2);
  19934. const lastPoint = [lastEdge[0], lastEdge[2]];
  19935. for (const edge of this.#verticalEdges) {
  19936. const [x, y1, y2] = edge;
  19937. edge[0] = (x - shiftedMinX) / bboxWidth;
  19938. edge[1] = (y1 - shiftedMinY) / bboxHeight;
  19939. edge[2] = (y2 - shiftedMinY) / bboxHeight;
  19940. }
  19941. this.#box = {
  19942. x: shiftedMinX,
  19943. y: shiftedMinY,
  19944. width: bboxWidth,
  19945. height: bboxHeight,
  19946. lastPoint
  19947. };
  19948. }
  19949. getOutlines() {
  19950. this.#verticalEdges.sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]);
  19951. const outlineVerticalEdges = [];
  19952. for (const edge of this.#verticalEdges) {
  19953. if (edge[3]) {
  19954. outlineVerticalEdges.push(...this.#breakEdge(edge));
  19955. this.#insert(edge);
  19956. } else {
  19957. this.#remove(edge);
  19958. outlineVerticalEdges.push(...this.#breakEdge(edge));
  19959. }
  19960. }
  19961. return this.#getOutlines(outlineVerticalEdges);
  19962. }
  19963. #getOutlines(outlineVerticalEdges) {
  19964. const edges = [];
  19965. const allEdges = new Set();
  19966. for (const edge of outlineVerticalEdges) {
  19967. const [x, y1, y2] = edge;
  19968. edges.push([x, y1, edge], [x, y2, edge]);
  19969. }
  19970. edges.sort((a, b) => a[1] - b[1] || a[0] - b[0]);
  19971. for (let i = 0, ii = edges.length; i < ii; i += 2) {
  19972. const edge1 = edges[i][2];
  19973. const edge2 = edges[i + 1][2];
  19974. edge1.push(edge2);
  19975. edge2.push(edge1);
  19976. allEdges.add(edge1);
  19977. allEdges.add(edge2);
  19978. }
  19979. const outlines = [];
  19980. let outline;
  19981. while (allEdges.size > 0) {
  19982. const edge = allEdges.values().next().value;
  19983. let [x, y1, y2, edge1, edge2] = edge;
  19984. allEdges.delete(edge);
  19985. let lastPointX = x;
  19986. let lastPointY = y1;
  19987. outline = [x, y2];
  19988. outlines.push(outline);
  19989. while (true) {
  19990. let e;
  19991. if (allEdges.has(edge1)) {
  19992. e = edge1;
  19993. } else if (allEdges.has(edge2)) {
  19994. e = edge2;
  19995. } else {
  19996. break;
  19997. }
  19998. allEdges.delete(e);
  19999. [x, y1, y2, edge1, edge2] = e;
  20000. if (lastPointX !== x) {
  20001. outline.push(lastPointX, lastPointY, x, lastPointY === y1 ? y1 : y2);
  20002. lastPointX = x;
  20003. }
  20004. lastPointY = lastPointY === y1 ? y2 : y1;
  20005. }
  20006. outline.push(lastPointX, lastPointY);
  20007. }
  20008. return new HighlightOutline(outlines, this.#box);
  20009. }
  20010. #binarySearch(y) {
  20011. const array = this.#intervals;
  20012. let start = 0;
  20013. let end = array.length - 1;
  20014. while (start <= end) {
  20015. const middle = start + end >> 1;
  20016. const y1 = array[middle][0];
  20017. if (y1 === y) {
  20018. return middle;
  20019. }
  20020. if (y1 < y) {
  20021. start = middle + 1;
  20022. } else {
  20023. end = middle - 1;
  20024. }
  20025. }
  20026. return end + 1;
  20027. }
  20028. #insert([, y1, y2]) {
  20029. const index = this.#binarySearch(y1);
  20030. this.#intervals.splice(index, 0, [y1, y2]);
  20031. }
  20032. #remove([, y1, y2]) {
  20033. const index = this.#binarySearch(y1);
  20034. for (let i = index; i < this.#intervals.length; i++) {
  20035. const [start, end] = this.#intervals[i];
  20036. if (start !== y1) {
  20037. break;
  20038. }
  20039. if (start === y1 && end === y2) {
  20040. this.#intervals.splice(i, 1);
  20041. return;
  20042. }
  20043. }
  20044. for (let i = index - 1; i >= 0; i--) {
  20045. const [start, end] = this.#intervals[i];
  20046. if (start !== y1) {
  20047. break;
  20048. }
  20049. if (start === y1 && end === y2) {
  20050. this.#intervals.splice(i, 1);
  20051. return;
  20052. }
  20053. }
  20054. }
  20055. #breakEdge(edge) {
  20056. const [x, y1, y2] = edge;
  20057. const results = [[x, y1, y2]];
  20058. const index = this.#binarySearch(y2);
  20059. for (let i = 0; i < index; i++) {
  20060. const [start, end] = this.#intervals[i];
  20061. for (let j = 0, jj = results.length; j < jj; j++) {
  20062. const [, y3, y4] = results[j];
  20063. if (end <= y3 || y4 <= start) {
  20064. continue;
  20065. }
  20066. if (y3 >= start) {
  20067. if (y4 > end) {
  20068. results[j][1] = end;
  20069. } else {
  20070. if (jj === 1) {
  20071. return [];
  20072. }
  20073. results.splice(j, 1);
  20074. j--;
  20075. jj--;
  20076. }
  20077. continue;
  20078. }
  20079. results[j][2] = start;
  20080. if (y4 > end) {
  20081. results.push([x, end, y4]);
  20082. }
  20083. }
  20084. }
  20085. return results;
  20086. }
  20087. }
  20088. class Outline {
  20089. toSVGPath() {
  20090. throw new Error("Abstract method `toSVGPath` must be implemented.");
  20091. }
  20092. get box() {
  20093. throw new Error("Abstract getter `box` must be implemented.");
  20094. }
  20095. serialize(_bbox, _rotation) {
  20096. throw new Error("Abstract method `serialize` must be implemented.");
  20097. }
  20098. get free() {
  20099. return this instanceof FreeHighlightOutline;
  20100. }
  20101. }
  20102. class HighlightOutline extends Outline {
  20103. #box;
  20104. #outlines;
  20105. constructor(outlines, box) {
  20106. super();
  20107. this.#outlines = outlines;
  20108. this.#box = box;
  20109. }
  20110. toSVGPath() {
  20111. const buffer = [];
  20112. for (const polygon of this.#outlines) {
  20113. let [prevX, prevY] = polygon;
  20114. buffer.push(`M${prevX} ${prevY}`);
  20115. for (let i = 2; i < polygon.length; i += 2) {
  20116. const x = polygon[i];
  20117. const y = polygon[i + 1];
  20118. if (x === prevX) {
  20119. buffer.push(`V${y}`);
  20120. prevY = y;
  20121. } else if (y === prevY) {
  20122. buffer.push(`H${x}`);
  20123. prevX = x;
  20124. }
  20125. }
  20126. buffer.push("Z");
  20127. }
  20128. return buffer.join(" ");
  20129. }
  20130. serialize([blX, blY, trX, trY], _rotation) {
  20131. const outlines = [];
  20132. const width = trX - blX;
  20133. const height = trY - blY;
  20134. for (const outline of this.#outlines) {
  20135. const points = new Array(outline.length);
  20136. for (let i = 0; i < outline.length; i += 2) {
  20137. points[i] = blX + outline[i] * width;
  20138. points[i + 1] = trY - outline[i + 1] * height;
  20139. }
  20140. outlines.push(points);
  20141. }
  20142. return outlines;
  20143. }
  20144. get box() {
  20145. return this.#box;
  20146. }
  20147. }
  20148. class FreeOutliner {
  20149. #box;
  20150. #bottom = [];
  20151. #innerMargin;
  20152. #isLTR;
  20153. #top = [];
  20154. #last = new Float64Array(18);
  20155. #lastX;
  20156. #lastY;
  20157. #min;
  20158. #min_dist;
  20159. #scaleFactor;
  20160. #thickness;
  20161. #points = [];
  20162. static #MIN_DIST = 8;
  20163. static #MIN_DIFF = 2;
  20164. static #MIN = FreeOutliner.#MIN_DIST + FreeOutliner.#MIN_DIFF;
  20165. constructor({
  20166. x,
  20167. y
  20168. }, box, scaleFactor, thickness, isLTR, innerMargin = 0) {
  20169. this.#box = box;
  20170. this.#thickness = thickness * scaleFactor;
  20171. this.#isLTR = isLTR;
  20172. this.#last.set([NaN, NaN, NaN, NaN, x, y], 6);
  20173. this.#innerMargin = innerMargin;
  20174. this.#min_dist = FreeOutliner.#MIN_DIST * scaleFactor;
  20175. this.#min = FreeOutliner.#MIN * scaleFactor;
  20176. this.#scaleFactor = scaleFactor;
  20177. this.#points.push(x, y);
  20178. }
  20179. get free() {
  20180. return true;
  20181. }
  20182. isEmpty() {
  20183. return isNaN(this.#last[8]);
  20184. }
  20185. #getLastCoords() {
  20186. const lastTop = this.#last.subarray(4, 6);
  20187. const lastBottom = this.#last.subarray(16, 18);
  20188. const [x, y, width, height] = this.#box;
  20189. return [(this.#lastX + (lastTop[0] - lastBottom[0]) / 2 - x) / width, (this.#lastY + (lastTop[1] - lastBottom[1]) / 2 - y) / height, (this.#lastX + (lastBottom[0] - lastTop[0]) / 2 - x) / width, (this.#lastY + (lastBottom[1] - lastTop[1]) / 2 - y) / height];
  20190. }
  20191. add({
  20192. x,
  20193. y
  20194. }) {
  20195. this.#lastX = x;
  20196. this.#lastY = y;
  20197. const [layerX, layerY, layerWidth, layerHeight] = this.#box;
  20198. let [x1, y1, x2, y2] = this.#last.subarray(8, 12);
  20199. const diffX = x - x2;
  20200. const diffY = y - y2;
  20201. const d = Math.hypot(diffX, diffY);
  20202. if (d < this.#min) {
  20203. return false;
  20204. }
  20205. const diffD = d - this.#min_dist;
  20206. const K = diffD / d;
  20207. const shiftX = K * diffX;
  20208. const shiftY = K * diffY;
  20209. let x0 = x1;
  20210. let y0 = y1;
  20211. x1 = x2;
  20212. y1 = y2;
  20213. x2 += shiftX;
  20214. y2 += shiftY;
  20215. this.#points?.push(x, y);
  20216. const nX = -shiftY / diffD;
  20217. const nY = shiftX / diffD;
  20218. const thX = nX * this.#thickness;
  20219. const thY = nY * this.#thickness;
  20220. this.#last.set(this.#last.subarray(2, 8), 0);
  20221. this.#last.set([x2 + thX, y2 + thY], 4);
  20222. this.#last.set(this.#last.subarray(14, 18), 12);
  20223. this.#last.set([x2 - thX, y2 - thY], 16);
  20224. if (isNaN(this.#last[6])) {
  20225. if (this.#top.length === 0) {
  20226. this.#last.set([x1 + thX, y1 + thY], 2);
  20227. this.#top.push(NaN, NaN, NaN, NaN, (x1 + thX - layerX) / layerWidth, (y1 + thY - layerY) / layerHeight);
  20228. this.#last.set([x1 - thX, y1 - thY], 14);
  20229. this.#bottom.push(NaN, NaN, NaN, NaN, (x1 - thX - layerX) / layerWidth, (y1 - thY - layerY) / layerHeight);
  20230. }
  20231. this.#last.set([x0, y0, x1, y1, x2, y2], 6);
  20232. return !this.isEmpty();
  20233. }
  20234. this.#last.set([x0, y0, x1, y1, x2, y2], 6);
  20235. const angle = Math.abs(Math.atan2(y0 - y1, x0 - x1) - Math.atan2(shiftY, shiftX));
  20236. if (angle < Math.PI / 2) {
  20237. [x1, y1, x2, y2] = this.#last.subarray(2, 6);
  20238. this.#top.push(NaN, NaN, NaN, NaN, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight);
  20239. [x1, y1, x0, y0] = this.#last.subarray(14, 18);
  20240. this.#bottom.push(NaN, NaN, NaN, NaN, ((x0 + x1) / 2 - layerX) / layerWidth, ((y0 + y1) / 2 - layerY) / layerHeight);
  20241. return true;
  20242. }
  20243. [x0, y0, x1, y1, x2, y2] = this.#last.subarray(0, 6);
  20244. this.#top.push(((x0 + 5 * x1) / 6 - layerX) / layerWidth, ((y0 + 5 * y1) / 6 - layerY) / layerHeight, ((5 * x1 + x2) / 6 - layerX) / layerWidth, ((5 * y1 + y2) / 6 - layerY) / layerHeight, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight);
  20245. [x2, y2, x1, y1, x0, y0] = this.#last.subarray(12, 18);
  20246. this.#bottom.push(((x0 + 5 * x1) / 6 - layerX) / layerWidth, ((y0 + 5 * y1) / 6 - layerY) / layerHeight, ((5 * x1 + x2) / 6 - layerX) / layerWidth, ((5 * y1 + y2) / 6 - layerY) / layerHeight, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight);
  20247. return true;
  20248. }
  20249. toSVGPath() {
  20250. if (this.isEmpty()) {
  20251. return "";
  20252. }
  20253. const top = this.#top;
  20254. const bottom = this.#bottom;
  20255. const lastTop = this.#last.subarray(4, 6);
  20256. const lastBottom = this.#last.subarray(16, 18);
  20257. const [x, y, width, height] = this.#box;
  20258. const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
  20259. if (isNaN(this.#last[6]) && !this.isEmpty()) {
  20260. return `M${(this.#last[2] - x) / width} ${(this.#last[3] - y) / height} L${(this.#last[4] - x) / width} ${(this.#last[5] - y) / height} L${lastTopX} ${lastTopY} L${lastBottomX} ${lastBottomY} L${(this.#last[16] - x) / width} ${(this.#last[17] - y) / height} L${(this.#last[14] - x) / width} ${(this.#last[15] - y) / height} Z`;
  20261. }
  20262. const buffer = [];
  20263. buffer.push(`M${top[4]} ${top[5]}`);
  20264. for (let i = 6; i < top.length; i += 6) {
  20265. if (isNaN(top[i])) {
  20266. buffer.push(`L${top[i + 4]} ${top[i + 5]}`);
  20267. } else {
  20268. buffer.push(`C${top[i]} ${top[i + 1]} ${top[i + 2]} ${top[i + 3]} ${top[i + 4]} ${top[i + 5]}`);
  20269. }
  20270. }
  20271. buffer.push(`L${(lastTop[0] - x) / width} ${(lastTop[1] - y) / height} L${lastTopX} ${lastTopY} L${lastBottomX} ${lastBottomY} L${(lastBottom[0] - x) / width} ${(lastBottom[1] - y) / height}`);
  20272. for (let i = bottom.length - 6; i >= 6; i -= 6) {
  20273. if (isNaN(bottom[i])) {
  20274. buffer.push(`L${bottom[i + 4]} ${bottom[i + 5]}`);
  20275. } else {
  20276. buffer.push(`C${bottom[i]} ${bottom[i + 1]} ${bottom[i + 2]} ${bottom[i + 3]} ${bottom[i + 4]} ${bottom[i + 5]}`);
  20277. }
  20278. }
  20279. buffer.push(`L${bottom[4]} ${bottom[5]} Z`);
  20280. return buffer.join(" ");
  20281. }
  20282. getOutlines() {
  20283. const top = this.#top;
  20284. const bottom = this.#bottom;
  20285. const last = this.#last;
  20286. const lastTop = last.subarray(4, 6);
  20287. const lastBottom = last.subarray(16, 18);
  20288. const [layerX, layerY, layerWidth, layerHeight] = this.#box;
  20289. const points = new Float64Array((this.#points?.length ?? 0) + 2);
  20290. for (let i = 0, ii = points.length - 2; i < ii; i += 2) {
  20291. points[i] = (this.#points[i] - layerX) / layerWidth;
  20292. points[i + 1] = (this.#points[i + 1] - layerY) / layerHeight;
  20293. }
  20294. points[points.length - 2] = (this.#lastX - layerX) / layerWidth;
  20295. points[points.length - 1] = (this.#lastY - layerY) / layerHeight;
  20296. const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
  20297. if (isNaN(last[6]) && !this.isEmpty()) {
  20298. const outline = new Float64Array(36);
  20299. outline.set([NaN, NaN, NaN, NaN, (last[2] - layerX) / layerWidth, (last[3] - layerY) / layerHeight, NaN, NaN, NaN, NaN, (last[4] - layerX) / layerWidth, (last[5] - layerY) / layerHeight, NaN, NaN, NaN, NaN, lastTopX, lastTopY, NaN, NaN, NaN, NaN, lastBottomX, lastBottomY, NaN, NaN, NaN, NaN, (last[16] - layerX) / layerWidth, (last[17] - layerY) / layerHeight, NaN, NaN, NaN, NaN, (last[14] - layerX) / layerWidth, (last[15] - layerY) / layerHeight], 0);
  20300. return new FreeHighlightOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR);
  20301. }
  20302. const outline = new Float64Array(this.#top.length + 24 + this.#bottom.length);
  20303. let N = top.length;
  20304. for (let i = 0; i < N; i += 2) {
  20305. if (isNaN(top[i])) {
  20306. outline[i] = outline[i + 1] = NaN;
  20307. continue;
  20308. }
  20309. outline[i] = top[i];
  20310. outline[i + 1] = top[i + 1];
  20311. }
  20312. outline.set([NaN, NaN, NaN, NaN, (lastTop[0] - layerX) / layerWidth, (lastTop[1] - layerY) / layerHeight, NaN, NaN, NaN, NaN, lastTopX, lastTopY, NaN, NaN, NaN, NaN, lastBottomX, lastBottomY, NaN, NaN, NaN, NaN, (lastBottom[0] - layerX) / layerWidth, (lastBottom[1] - layerY) / layerHeight], N);
  20313. N += 24;
  20314. for (let i = bottom.length - 6; i >= 6; i -= 6) {
  20315. for (let j = 0; j < 6; j += 2) {
  20316. if (isNaN(bottom[i + j])) {
  20317. outline[N] = outline[N + 1] = NaN;
  20318. N += 2;
  20319. continue;
  20320. }
  20321. outline[N] = bottom[i + j];
  20322. outline[N + 1] = bottom[i + j + 1];
  20323. N += 2;
  20324. }
  20325. }
  20326. outline.set([NaN, NaN, NaN, NaN, bottom[4], bottom[5]], N);
  20327. return new FreeHighlightOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR);
  20328. }
  20329. }
  20330. class FreeHighlightOutline extends Outline {
  20331. #box;
  20332. #bbox = null;
  20333. #innerMargin;
  20334. #isLTR;
  20335. #points;
  20336. #scaleFactor;
  20337. #outline;
  20338. constructor(outline, points, box, scaleFactor, innerMargin, isLTR) {
  20339. super();
  20340. this.#outline = outline;
  20341. this.#points = points;
  20342. this.#box = box;
  20343. this.#scaleFactor = scaleFactor;
  20344. this.#innerMargin = innerMargin;
  20345. this.#isLTR = isLTR;
  20346. this.#computeMinMax(isLTR);
  20347. const {
  20348. x,
  20349. y,
  20350. width,
  20351. height
  20352. } = this.#bbox;
  20353. for (let i = 0, ii = outline.length; i < ii; i += 2) {
  20354. outline[i] = (outline[i] - x) / width;
  20355. outline[i + 1] = (outline[i + 1] - y) / height;
  20356. }
  20357. for (let i = 0, ii = points.length; i < ii; i += 2) {
  20358. points[i] = (points[i] - x) / width;
  20359. points[i + 1] = (points[i + 1] - y) / height;
  20360. }
  20361. }
  20362. toSVGPath() {
  20363. const buffer = [`M${this.#outline[4]} ${this.#outline[5]}`];
  20364. for (let i = 6, ii = this.#outline.length; i < ii; i += 6) {
  20365. if (isNaN(this.#outline[i])) {
  20366. buffer.push(`L${this.#outline[i + 4]} ${this.#outline[i + 5]}`);
  20367. continue;
  20368. }
  20369. buffer.push(`C${this.#outline[i]} ${this.#outline[i + 1]} ${this.#outline[i + 2]} ${this.#outline[i + 3]} ${this.#outline[i + 4]} ${this.#outline[i + 5]}`);
  20370. }
  20371. buffer.push("Z");
  20372. return buffer.join(" ");
  20373. }
  20374. serialize([blX, blY, trX, trY], rotation) {
  20375. const width = trX - blX;
  20376. const height = trY - blY;
  20377. let outline;
  20378. let points;
  20379. switch (rotation) {
  20380. case 0:
  20381. outline = this.#rescale(this.#outline, blX, trY, width, -height);
  20382. points = this.#rescale(this.#points, blX, trY, width, -height);
  20383. break;
  20384. case 90:
  20385. outline = this.#rescaleAndSwap(this.#outline, blX, blY, width, height);
  20386. points = this.#rescaleAndSwap(this.#points, blX, blY, width, height);
  20387. break;
  20388. case 180:
  20389. outline = this.#rescale(this.#outline, trX, blY, -width, height);
  20390. points = this.#rescale(this.#points, trX, blY, -width, height);
  20391. break;
  20392. case 270:
  20393. outline = this.#rescaleAndSwap(this.#outline, trX, trY, -width, -height);
  20394. points = this.#rescaleAndSwap(this.#points, trX, trY, -width, -height);
  20395. break;
  20396. }
  20397. return {
  20398. outline: Array.from(outline),
  20399. points: [Array.from(points)]
  20400. };
  20401. }
  20402. #rescale(src, tx, ty, sx, sy) {
  20403. const dest = new Float64Array(src.length);
  20404. for (let i = 0, ii = src.length; i < ii; i += 2) {
  20405. dest[i] = tx + src[i] * sx;
  20406. dest[i + 1] = ty + src[i + 1] * sy;
  20407. }
  20408. return dest;
  20409. }
  20410. #rescaleAndSwap(src, tx, ty, sx, sy) {
  20411. const dest = new Float64Array(src.length);
  20412. for (let i = 0, ii = src.length; i < ii; i += 2) {
  20413. dest[i] = tx + src[i + 1] * sx;
  20414. dest[i + 1] = ty + src[i] * sy;
  20415. }
  20416. return dest;
  20417. }
  20418. #computeMinMax(isLTR) {
  20419. const outline = this.#outline;
  20420. let lastX = outline[4];
  20421. let lastY = outline[5];
  20422. let minX = lastX;
  20423. let minY = lastY;
  20424. let maxX = lastX;
  20425. let maxY = lastY;
  20426. let lastPointX = lastX;
  20427. let lastPointY = lastY;
  20428. const ltrCallback = isLTR ? Math.max : Math.min;
  20429. for (let i = 6, ii = outline.length; i < ii; i += 6) {
  20430. if (isNaN(outline[i])) {
  20431. minX = Math.min(minX, outline[i + 4]);
  20432. minY = Math.min(minY, outline[i + 5]);
  20433. maxX = Math.max(maxX, outline[i + 4]);
  20434. maxY = Math.max(maxY, outline[i + 5]);
  20435. if (lastPointY < outline[i + 5]) {
  20436. lastPointX = outline[i + 4];
  20437. lastPointY = outline[i + 5];
  20438. } else if (lastPointY === outline[i + 5]) {
  20439. lastPointX = ltrCallback(lastPointX, outline[i + 4]);
  20440. }
  20441. } else {
  20442. const bbox = Util.bezierBoundingBox(lastX, lastY, ...outline.slice(i, i + 6));
  20443. minX = Math.min(minX, bbox[0]);
  20444. minY = Math.min(minY, bbox[1]);
  20445. maxX = Math.max(maxX, bbox[2]);
  20446. maxY = Math.max(maxY, bbox[3]);
  20447. if (lastPointY < bbox[3]) {
  20448. lastPointX = bbox[2];
  20449. lastPointY = bbox[3];
  20450. } else if (lastPointY === bbox[3]) {
  20451. lastPointX = ltrCallback(lastPointX, bbox[2]);
  20452. }
  20453. }
  20454. lastX = outline[i + 4];
  20455. lastY = outline[i + 5];
  20456. }
  20457. const x = minX - this.#innerMargin,
  20458. y = minY - this.#innerMargin,
  20459. width = maxX - minX + 2 * this.#innerMargin,
  20460. height = maxY - minY + 2 * this.#innerMargin;
  20461. this.#bbox = {
  20462. x,
  20463. y,
  20464. width,
  20465. height,
  20466. lastPoint: [lastPointX, lastPointY]
  20467. };
  20468. }
  20469. get box() {
  20470. return this.#bbox;
  20471. }
  20472. getNewOutline(thickness, innerMargin) {
  20473. const {
  20474. x,
  20475. y,
  20476. width,
  20477. height
  20478. } = this.#bbox;
  20479. const [layerX, layerY, layerWidth, layerHeight] = this.#box;
  20480. const sx = width * layerWidth;
  20481. const sy = height * layerHeight;
  20482. const tx = x * layerWidth + layerX;
  20483. const ty = y * layerHeight + layerY;
  20484. const outliner = new FreeOutliner({
  20485. x: this.#points[0] * sx + tx,
  20486. y: this.#points[1] * sy + ty
  20487. }, this.#box, this.#scaleFactor, thickness, this.#isLTR, innerMargin ?? this.#innerMargin);
  20488. for (let i = 2; i < this.#points.length; i += 2) {
  20489. outliner.add({
  20490. x: this.#points[i] * sx + tx,
  20491. y: this.#points[i + 1] * sy + ty
  20492. });
  20493. }
  20494. return outliner.getOutlines();
  20495. }
  20496. }
  20497. ;// ./src/display/editor/color_picker.js
  20498. class ColorPicker {
  20499. #boundKeyDown = this.#keyDown.bind(this);
  20500. #boundPointerDown = this.#pointerDown.bind(this);
  20501. #button = null;
  20502. #buttonSwatch = null;
  20503. #defaultColor;
  20504. #dropdown = null;
  20505. #dropdownWasFromKeyboard = false;
  20506. #isMainColorPicker = false;
  20507. #editor = null;
  20508. #eventBus;
  20509. #uiManager = null;
  20510. #type;
  20511. static #l10nColor = null;
  20512. static get _keyboardManager() {
  20513. return shadow(this, "_keyboardManager", new KeyboardManager([[["Escape", "mac+Escape"], ColorPicker.prototype._hideDropdownFromKeyboard], [[" ", "mac+ "], ColorPicker.prototype._colorSelectFromKeyboard], [["ArrowDown", "ArrowRight", "mac+ArrowDown", "mac+ArrowRight"], ColorPicker.prototype._moveToNext], [["ArrowUp", "ArrowLeft", "mac+ArrowUp", "mac+ArrowLeft"], ColorPicker.prototype._moveToPrevious], [["Home", "mac+Home"], ColorPicker.prototype._moveToBeginning], [["End", "mac+End"], ColorPicker.prototype._moveToEnd]]));
  20514. }
  20515. constructor({
  20516. editor = null,
  20517. uiManager = null
  20518. }) {
  20519. if (editor) {
  20520. this.#isMainColorPicker = false;
  20521. this.#type = AnnotationEditorParamsType.HIGHLIGHT_COLOR;
  20522. this.#editor = editor;
  20523. } else {
  20524. this.#isMainColorPicker = true;
  20525. this.#type = AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR;
  20526. }
  20527. this.#uiManager = editor?._uiManager || uiManager;
  20528. this.#eventBus = this.#uiManager._eventBus;
  20529. this.#defaultColor = editor?.color || this.#uiManager?.highlightColors.values().next().value || "#FFFF98";
  20530. ColorPicker.#l10nColor ||= Object.freeze({
  20531. blue: "pdfjs-editor-colorpicker-blue",
  20532. green: "pdfjs-editor-colorpicker-green",
  20533. pink: "pdfjs-editor-colorpicker-pink",
  20534. red: "pdfjs-editor-colorpicker-red",
  20535. yellow: "pdfjs-editor-colorpicker-yellow"
  20536. });
  20537. }
  20538. renderButton() {
  20539. const button = this.#button = document.createElement("button");
  20540. button.className = "colorPicker";
  20541. button.tabIndex = "0";
  20542. button.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-button");
  20543. button.setAttribute("aria-haspopup", true);
  20544. const signal = this.#uiManager._signal;
  20545. button.addEventListener("click", this.#openDropdown.bind(this), {
  20546. signal
  20547. });
  20548. button.addEventListener("keydown", this.#boundKeyDown, {
  20549. signal
  20550. });
  20551. const swatch = this.#buttonSwatch = document.createElement("span");
  20552. swatch.className = "swatch";
  20553. swatch.setAttribute("aria-hidden", true);
  20554. swatch.style.backgroundColor = this.#defaultColor;
  20555. button.append(swatch);
  20556. return button;
  20557. }
  20558. renderMainDropdown() {
  20559. const dropdown = this.#dropdown = this.#getDropdownRoot();
  20560. dropdown.setAttribute("aria-orientation", "horizontal");
  20561. dropdown.setAttribute("aria-labelledby", "highlightColorPickerLabel");
  20562. return dropdown;
  20563. }
  20564. #getDropdownRoot() {
  20565. const div = document.createElement("div");
  20566. const signal = this.#uiManager._signal;
  20567. div.addEventListener("contextmenu", noContextMenu, {
  20568. signal
  20569. });
  20570. div.className = "dropdown";
  20571. div.role = "listbox";
  20572. div.setAttribute("aria-multiselectable", false);
  20573. div.setAttribute("aria-orientation", "vertical");
  20574. div.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-dropdown");
  20575. for (const [name, color] of this.#uiManager.highlightColors) {
  20576. const button = document.createElement("button");
  20577. button.tabIndex = "0";
  20578. button.role = "option";
  20579. button.setAttribute("data-color", color);
  20580. button.title = name;
  20581. button.setAttribute("data-l10n-id", ColorPicker.#l10nColor[name]);
  20582. const swatch = document.createElement("span");
  20583. button.append(swatch);
  20584. swatch.className = "swatch";
  20585. swatch.style.backgroundColor = color;
  20586. button.setAttribute("aria-selected", color === this.#defaultColor);
  20587. button.addEventListener("click", this.#colorSelect.bind(this, color), {
  20588. signal
  20589. });
  20590. div.append(button);
  20591. }
  20592. div.addEventListener("keydown", this.#boundKeyDown, {
  20593. signal
  20594. });
  20595. return div;
  20596. }
  20597. #colorSelect(color, event) {
  20598. event.stopPropagation();
  20599. this.#eventBus.dispatch("switchannotationeditorparams", {
  20600. source: this,
  20601. type: this.#type,
  20602. value: color
  20603. });
  20604. }
  20605. _colorSelectFromKeyboard(event) {
  20606. if (event.target === this.#button) {
  20607. this.#openDropdown(event);
  20608. return;
  20609. }
  20610. const color = event.target.getAttribute("data-color");
  20611. if (!color) {
  20612. return;
  20613. }
  20614. this.#colorSelect(color, event);
  20615. }
  20616. _moveToNext(event) {
  20617. if (!this.#isDropdownVisible) {
  20618. this.#openDropdown(event);
  20619. return;
  20620. }
  20621. if (event.target === this.#button) {
  20622. this.#dropdown.firstChild?.focus();
  20623. return;
  20624. }
  20625. event.target.nextSibling?.focus();
  20626. }
  20627. _moveToPrevious(event) {
  20628. if (event.target === this.#dropdown?.firstChild || event.target === this.#button) {
  20629. if (this.#isDropdownVisible) {
  20630. this._hideDropdownFromKeyboard();
  20631. }
  20632. return;
  20633. }
  20634. if (!this.#isDropdownVisible) {
  20635. this.#openDropdown(event);
  20636. }
  20637. event.target.previousSibling?.focus();
  20638. }
  20639. _moveToBeginning(event) {
  20640. if (!this.#isDropdownVisible) {
  20641. this.#openDropdown(event);
  20642. return;
  20643. }
  20644. this.#dropdown.firstChild?.focus();
  20645. }
  20646. _moveToEnd(event) {
  20647. if (!this.#isDropdownVisible) {
  20648. this.#openDropdown(event);
  20649. return;
  20650. }
  20651. this.#dropdown.lastChild?.focus();
  20652. }
  20653. #keyDown(event) {
  20654. ColorPicker._keyboardManager.exec(this, event);
  20655. }
  20656. #openDropdown(event) {
  20657. if (this.#isDropdownVisible) {
  20658. this.hideDropdown();
  20659. return;
  20660. }
  20661. this.#dropdownWasFromKeyboard = event.detail === 0;
  20662. window.addEventListener("pointerdown", this.#boundPointerDown, {
  20663. signal: this.#uiManager._signal
  20664. });
  20665. if (this.#dropdown) {
  20666. this.#dropdown.classList.remove("hidden");
  20667. return;
  20668. }
  20669. const root = this.#dropdown = this.#getDropdownRoot();
  20670. this.#button.append(root);
  20671. }
  20672. #pointerDown(event) {
  20673. if (this.#dropdown?.contains(event.target)) {
  20674. return;
  20675. }
  20676. this.hideDropdown();
  20677. }
  20678. hideDropdown() {
  20679. this.#dropdown?.classList.add("hidden");
  20680. window.removeEventListener("pointerdown", this.#boundPointerDown);
  20681. }
  20682. get #isDropdownVisible() {
  20683. return this.#dropdown && !this.#dropdown.classList.contains("hidden");
  20684. }
  20685. _hideDropdownFromKeyboard() {
  20686. if (this.#isMainColorPicker) {
  20687. return;
  20688. }
  20689. if (!this.#isDropdownVisible) {
  20690. this.#editor?.unselect();
  20691. return;
  20692. }
  20693. this.hideDropdown();
  20694. this.#button.focus({
  20695. preventScroll: true,
  20696. focusVisible: this.#dropdownWasFromKeyboard
  20697. });
  20698. }
  20699. updateColor(color) {
  20700. if (this.#buttonSwatch) {
  20701. this.#buttonSwatch.style.backgroundColor = color;
  20702. }
  20703. if (!this.#dropdown) {
  20704. return;
  20705. }
  20706. const i = this.#uiManager.highlightColors.values();
  20707. for (const child of this.#dropdown.children) {
  20708. child.setAttribute("aria-selected", i.next().value === color);
  20709. }
  20710. }
  20711. destroy() {
  20712. this.#button?.remove();
  20713. this.#button = null;
  20714. this.#buttonSwatch = null;
  20715. this.#dropdown?.remove();
  20716. this.#dropdown = null;
  20717. }
  20718. }
  20719. ;// ./src/display/editor/highlight.js
  20720. class HighlightEditor extends AnnotationEditor {
  20721. #anchorNode = null;
  20722. #anchorOffset = 0;
  20723. #boxes;
  20724. #clipPathId = null;
  20725. #colorPicker = null;
  20726. #focusOutlines = null;
  20727. #focusNode = null;
  20728. #focusOffset = 0;
  20729. #highlightDiv = null;
  20730. #highlightOutlines = null;
  20731. #id = null;
  20732. #isFreeHighlight = false;
  20733. #lastPoint = null;
  20734. #opacity;
  20735. #outlineId = null;
  20736. #text = "";
  20737. #thickness;
  20738. #methodOfCreation = "";
  20739. static _defaultColor = null;
  20740. static _defaultOpacity = 1;
  20741. static _defaultThickness = 12;
  20742. static _type = "highlight";
  20743. static _editorType = AnnotationEditorType.HIGHLIGHT;
  20744. static _freeHighlightId = -1;
  20745. static _freeHighlight = null;
  20746. static _freeHighlightClipId = "";
  20747. static get _keyboardManager() {
  20748. const proto = HighlightEditor.prototype;
  20749. return shadow(this, "_keyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], proto._moveCaret, {
  20750. args: [0]
  20751. }], [["ArrowRight", "mac+ArrowRight"], proto._moveCaret, {
  20752. args: [1]
  20753. }], [["ArrowUp", "mac+ArrowUp"], proto._moveCaret, {
  20754. args: [2]
  20755. }], [["ArrowDown", "mac+ArrowDown"], proto._moveCaret, {
  20756. args: [3]
  20757. }]]));
  20758. }
  20759. constructor(params) {
  20760. super({
  20761. ...params,
  20762. name: "highlightEditor"
  20763. });
  20764. this.color = params.color || HighlightEditor._defaultColor;
  20765. this.#thickness = params.thickness || HighlightEditor._defaultThickness;
  20766. this.#opacity = params.opacity || HighlightEditor._defaultOpacity;
  20767. this.#boxes = params.boxes || null;
  20768. this.#methodOfCreation = params.methodOfCreation || "";
  20769. this.#text = params.text || "";
  20770. this._isDraggable = false;
  20771. if (params.highlightId > -1) {
  20772. this.#isFreeHighlight = true;
  20773. this.#createFreeOutlines(params);
  20774. this.#addToDrawLayer();
  20775. } else if (this.#boxes) {
  20776. this.#anchorNode = params.anchorNode;
  20777. this.#anchorOffset = params.anchorOffset;
  20778. this.#focusNode = params.focusNode;
  20779. this.#focusOffset = params.focusOffset;
  20780. this.#createOutlines();
  20781. this.#addToDrawLayer();
  20782. this.rotate(this.rotation);
  20783. }
  20784. }
  20785. get telemetryInitialData() {
  20786. return {
  20787. action: "added",
  20788. type: this.#isFreeHighlight ? "free_highlight" : "highlight",
  20789. color: this._uiManager.highlightColorNames.get(this.color),
  20790. thickness: this.#thickness,
  20791. methodOfCreation: this.#methodOfCreation
  20792. };
  20793. }
  20794. get telemetryFinalData() {
  20795. return {
  20796. type: "highlight",
  20797. color: this._uiManager.highlightColorNames.get(this.color)
  20798. };
  20799. }
  20800. static computeTelemetryFinalData(data) {
  20801. return {
  20802. numberOfColors: data.get("color").size
  20803. };
  20804. }
  20805. #createOutlines() {
  20806. const outliner = new Outliner(this.#boxes, 0.001);
  20807. this.#highlightOutlines = outliner.getOutlines();
  20808. ({
  20809. x: this.x,
  20810. y: this.y,
  20811. width: this.width,
  20812. height: this.height
  20813. } = this.#highlightOutlines.box);
  20814. const outlinerForOutline = new Outliner(this.#boxes, 0.0025, 0.001, this._uiManager.direction === "ltr");
  20815. this.#focusOutlines = outlinerForOutline.getOutlines();
  20816. const {
  20817. lastPoint
  20818. } = this.#focusOutlines.box;
  20819. this.#lastPoint = [(lastPoint[0] - this.x) / this.width, (lastPoint[1] - this.y) / this.height];
  20820. }
  20821. #createFreeOutlines({
  20822. highlightOutlines,
  20823. highlightId,
  20824. clipPathId
  20825. }) {
  20826. this.#highlightOutlines = highlightOutlines;
  20827. const extraThickness = 1.5;
  20828. this.#focusOutlines = highlightOutlines.getNewOutline(this.#thickness / 2 + extraThickness, 0.0025);
  20829. if (highlightId >= 0) {
  20830. this.#id = highlightId;
  20831. this.#clipPathId = clipPathId;
  20832. this.parent.drawLayer.finalizeLine(highlightId, highlightOutlines);
  20833. this.#outlineId = this.parent.drawLayer.highlightOutline(this.#focusOutlines);
  20834. } else if (this.parent) {
  20835. const angle = this.parent.viewport.rotation;
  20836. this.parent.drawLayer.updateLine(this.#id, highlightOutlines);
  20837. this.parent.drawLayer.updateBox(this.#id, HighlightEditor.#rotateBbox(this.#highlightOutlines.box, (angle - this.rotation + 360) % 360));
  20838. this.parent.drawLayer.updateLine(this.#outlineId, this.#focusOutlines);
  20839. this.parent.drawLayer.updateBox(this.#outlineId, HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle));
  20840. }
  20841. const {
  20842. x,
  20843. y,
  20844. width,
  20845. height
  20846. } = highlightOutlines.box;
  20847. switch (this.rotation) {
  20848. case 0:
  20849. this.x = x;
  20850. this.y = y;
  20851. this.width = width;
  20852. this.height = height;
  20853. break;
  20854. case 90:
  20855. {
  20856. const [pageWidth, pageHeight] = this.parentDimensions;
  20857. this.x = y;
  20858. this.y = 1 - x;
  20859. this.width = width * pageHeight / pageWidth;
  20860. this.height = height * pageWidth / pageHeight;
  20861. break;
  20862. }
  20863. case 180:
  20864. this.x = 1 - x;
  20865. this.y = 1 - y;
  20866. this.width = width;
  20867. this.height = height;
  20868. break;
  20869. case 270:
  20870. {
  20871. const [pageWidth, pageHeight] = this.parentDimensions;
  20872. this.x = 1 - y;
  20873. this.y = x;
  20874. this.width = width * pageHeight / pageWidth;
  20875. this.height = height * pageWidth / pageHeight;
  20876. break;
  20877. }
  20878. }
  20879. const {
  20880. lastPoint
  20881. } = this.#focusOutlines.box;
  20882. this.#lastPoint = [(lastPoint[0] - x) / width, (lastPoint[1] - y) / height];
  20883. }
  20884. static initialize(l10n, uiManager) {
  20885. AnnotationEditor.initialize(l10n, uiManager);
  20886. HighlightEditor._defaultColor ||= uiManager.highlightColors?.values().next().value || "#fff066";
  20887. }
  20888. static updateDefaultParams(type, value) {
  20889. switch (type) {
  20890. case AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:
  20891. HighlightEditor._defaultColor = value;
  20892. break;
  20893. case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:
  20894. HighlightEditor._defaultThickness = value;
  20895. break;
  20896. }
  20897. }
  20898. translateInPage(x, y) {}
  20899. get toolbarPosition() {
  20900. return this.#lastPoint;
  20901. }
  20902. updateParams(type, value) {
  20903. switch (type) {
  20904. case AnnotationEditorParamsType.HIGHLIGHT_COLOR:
  20905. this.#updateColor(value);
  20906. break;
  20907. case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:
  20908. this.#updateThickness(value);
  20909. break;
  20910. }
  20911. }
  20912. static get defaultPropertiesToUpdate() {
  20913. return [[AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR, HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, HighlightEditor._defaultThickness]];
  20914. }
  20915. get propertiesToUpdate() {
  20916. return [[AnnotationEditorParamsType.HIGHLIGHT_COLOR, this.color || HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, this.#thickness || HighlightEditor._defaultThickness], [AnnotationEditorParamsType.HIGHLIGHT_FREE, this.#isFreeHighlight]];
  20917. }
  20918. #updateColor(color) {
  20919. const setColorAndOpacity = (col, opa) => {
  20920. this.color = col;
  20921. this.parent?.drawLayer.changeColor(this.#id, col);
  20922. this.#colorPicker?.updateColor(col);
  20923. this.#opacity = opa;
  20924. this.parent?.drawLayer.changeOpacity(this.#id, opa);
  20925. };
  20926. const savedColor = this.color;
  20927. const savedOpacity = this.#opacity;
  20928. this.addCommands({
  20929. cmd: setColorAndOpacity.bind(this, color, HighlightEditor._defaultOpacity),
  20930. undo: setColorAndOpacity.bind(this, savedColor, savedOpacity),
  20931. post: this._uiManager.updateUI.bind(this._uiManager, this),
  20932. mustExec: true,
  20933. type: AnnotationEditorParamsType.HIGHLIGHT_COLOR,
  20934. overwriteIfSameType: true,
  20935. keepUndo: true
  20936. });
  20937. this._reportTelemetry({
  20938. action: "color_changed",
  20939. color: this._uiManager.highlightColorNames.get(color)
  20940. }, true);
  20941. }
  20942. #updateThickness(thickness) {
  20943. const savedThickness = this.#thickness;
  20944. const setThickness = th => {
  20945. this.#thickness = th;
  20946. this.#changeThickness(th);
  20947. };
  20948. this.addCommands({
  20949. cmd: setThickness.bind(this, thickness),
  20950. undo: setThickness.bind(this, savedThickness),
  20951. post: this._uiManager.updateUI.bind(this._uiManager, this),
  20952. mustExec: true,
  20953. type: AnnotationEditorParamsType.INK_THICKNESS,
  20954. overwriteIfSameType: true,
  20955. keepUndo: true
  20956. });
  20957. this._reportTelemetry({
  20958. action: "thickness_changed",
  20959. thickness
  20960. }, true);
  20961. }
  20962. async addEditToolbar() {
  20963. const toolbar = await super.addEditToolbar();
  20964. if (!toolbar) {
  20965. return null;
  20966. }
  20967. if (this._uiManager.highlightColors) {
  20968. this.#colorPicker = new ColorPicker({
  20969. editor: this
  20970. });
  20971. toolbar.addColorPicker(this.#colorPicker);
  20972. }
  20973. return toolbar;
  20974. }
  20975. disableEditing() {
  20976. super.disableEditing();
  20977. this.div.classList.toggle("disabled", true);
  20978. }
  20979. enableEditing() {
  20980. super.enableEditing();
  20981. this.div.classList.toggle("disabled", false);
  20982. }
  20983. fixAndSetPosition() {
  20984. return super.fixAndSetPosition(this.#getRotation());
  20985. }
  20986. getBaseTranslation() {
  20987. return [0, 0];
  20988. }
  20989. getRect(tx, ty) {
  20990. return super.getRect(tx, ty, this.#getRotation());
  20991. }
  20992. onceAdded() {
  20993. if (!this.annotationElementId) {
  20994. this.parent.addUndoableEditor(this);
  20995. }
  20996. this.div.focus();
  20997. }
  20998. remove() {
  20999. this.#cleanDrawLayer();
  21000. this._reportTelemetry({
  21001. action: "deleted"
  21002. });
  21003. super.remove();
  21004. }
  21005. rebuild() {
  21006. if (!this.parent) {
  21007. return;
  21008. }
  21009. super.rebuild();
  21010. if (this.div === null) {
  21011. return;
  21012. }
  21013. this.#addToDrawLayer();
  21014. if (!this.isAttachedToDOM) {
  21015. this.parent.add(this);
  21016. }
  21017. }
  21018. setParent(parent) {
  21019. let mustBeSelected = false;
  21020. if (this.parent && !parent) {
  21021. this.#cleanDrawLayer();
  21022. } else if (parent) {
  21023. this.#addToDrawLayer(parent);
  21024. mustBeSelected = !this.parent && this.div?.classList.contains("selectedEditor");
  21025. }
  21026. super.setParent(parent);
  21027. this.show(this._isVisible);
  21028. if (mustBeSelected) {
  21029. this.select();
  21030. }
  21031. }
  21032. #changeThickness(thickness) {
  21033. if (!this.#isFreeHighlight) {
  21034. return;
  21035. }
  21036. this.#createFreeOutlines({
  21037. highlightOutlines: this.#highlightOutlines.getNewOutline(thickness / 2)
  21038. });
  21039. this.fixAndSetPosition();
  21040. const [parentWidth, parentHeight] = this.parentDimensions;
  21041. this.setDims(this.width * parentWidth, this.height * parentHeight);
  21042. }
  21043. #cleanDrawLayer() {
  21044. if (this.#id === null || !this.parent) {
  21045. return;
  21046. }
  21047. this.parent.drawLayer.remove(this.#id);
  21048. this.#id = null;
  21049. this.parent.drawLayer.remove(this.#outlineId);
  21050. this.#outlineId = null;
  21051. }
  21052. #addToDrawLayer(parent = this.parent) {
  21053. if (this.#id !== null) {
  21054. return;
  21055. }
  21056. ({
  21057. id: this.#id,
  21058. clipPathId: this.#clipPathId
  21059. } = parent.drawLayer.highlight(this.#highlightOutlines, this.color, this.#opacity));
  21060. this.#outlineId = parent.drawLayer.highlightOutline(this.#focusOutlines);
  21061. if (this.#highlightDiv) {
  21062. this.#highlightDiv.style.clipPath = this.#clipPathId;
  21063. }
  21064. }
  21065. static #rotateBbox({
  21066. x,
  21067. y,
  21068. width,
  21069. height
  21070. }, angle) {
  21071. switch (angle) {
  21072. case 90:
  21073. return {
  21074. x: 1 - y - height,
  21075. y: x,
  21076. width: height,
  21077. height: width
  21078. };
  21079. case 180:
  21080. return {
  21081. x: 1 - x - width,
  21082. y: 1 - y - height,
  21083. width,
  21084. height
  21085. };
  21086. case 270:
  21087. return {
  21088. x: y,
  21089. y: 1 - x - width,
  21090. width: height,
  21091. height: width
  21092. };
  21093. }
  21094. return {
  21095. x,
  21096. y,
  21097. width,
  21098. height
  21099. };
  21100. }
  21101. rotate(angle) {
  21102. const {
  21103. drawLayer
  21104. } = this.parent;
  21105. let box;
  21106. if (this.#isFreeHighlight) {
  21107. angle = (angle - this.rotation + 360) % 360;
  21108. box = HighlightEditor.#rotateBbox(this.#highlightOutlines.box, angle);
  21109. } else {
  21110. box = HighlightEditor.#rotateBbox(this, angle);
  21111. }
  21112. drawLayer.rotate(this.#id, angle);
  21113. drawLayer.rotate(this.#outlineId, angle);
  21114. drawLayer.updateBox(this.#id, box);
  21115. drawLayer.updateBox(this.#outlineId, HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle));
  21116. }
  21117. render() {
  21118. if (this.div) {
  21119. return this.div;
  21120. }
  21121. const div = super.render();
  21122. if (this.#text) {
  21123. div.setAttribute("aria-label", this.#text);
  21124. div.setAttribute("role", "mark");
  21125. }
  21126. if (this.#isFreeHighlight) {
  21127. div.classList.add("free");
  21128. } else {
  21129. this.div.addEventListener("keydown", this.#keydown.bind(this), {
  21130. signal: this._uiManager._signal
  21131. });
  21132. }
  21133. const highlightDiv = this.#highlightDiv = document.createElement("div");
  21134. div.append(highlightDiv);
  21135. highlightDiv.setAttribute("aria-hidden", "true");
  21136. highlightDiv.className = "internal";
  21137. highlightDiv.style.clipPath = this.#clipPathId;
  21138. const [parentWidth, parentHeight] = this.parentDimensions;
  21139. this.setDims(this.width * parentWidth, this.height * parentHeight);
  21140. bindEvents(this, this.#highlightDiv, ["pointerover", "pointerleave"]);
  21141. this.enableEditing();
  21142. return div;
  21143. }
  21144. pointerover() {
  21145. this.parent.drawLayer.addClass(this.#outlineId, "hovered");
  21146. }
  21147. pointerleave() {
  21148. this.parent.drawLayer.removeClass(this.#outlineId, "hovered");
  21149. }
  21150. #keydown(event) {
  21151. HighlightEditor._keyboardManager.exec(this, event);
  21152. }
  21153. _moveCaret(direction) {
  21154. this.parent.unselect(this);
  21155. switch (direction) {
  21156. case 0:
  21157. case 2:
  21158. this.#setCaret(true);
  21159. break;
  21160. case 1:
  21161. case 3:
  21162. this.#setCaret(false);
  21163. break;
  21164. }
  21165. }
  21166. #setCaret(start) {
  21167. if (!this.#anchorNode) {
  21168. return;
  21169. }
  21170. const selection = window.getSelection();
  21171. if (start) {
  21172. selection.setPosition(this.#anchorNode, this.#anchorOffset);
  21173. } else {
  21174. selection.setPosition(this.#focusNode, this.#focusOffset);
  21175. }
  21176. }
  21177. select() {
  21178. super.select();
  21179. if (!this.#outlineId) {
  21180. return;
  21181. }
  21182. this.parent?.drawLayer.removeClass(this.#outlineId, "hovered");
  21183. this.parent?.drawLayer.addClass(this.#outlineId, "selected");
  21184. }
  21185. unselect() {
  21186. super.unselect();
  21187. if (!this.#outlineId) {
  21188. return;
  21189. }
  21190. this.parent?.drawLayer.removeClass(this.#outlineId, "selected");
  21191. if (!this.#isFreeHighlight) {
  21192. this.#setCaret(false);
  21193. }
  21194. }
  21195. get _mustFixPosition() {
  21196. return !this.#isFreeHighlight;
  21197. }
  21198. show(visible = this._isVisible) {
  21199. super.show(visible);
  21200. if (this.parent) {
  21201. this.parent.drawLayer.show(this.#id, visible);
  21202. this.parent.drawLayer.show(this.#outlineId, visible);
  21203. }
  21204. }
  21205. #getRotation() {
  21206. return this.#isFreeHighlight ? this.rotation : 0;
  21207. }
  21208. #serializeBoxes() {
  21209. if (this.#isFreeHighlight) {
  21210. return null;
  21211. }
  21212. const [pageWidth, pageHeight] = this.pageDimensions;
  21213. const [pageX, pageY] = this.pageTranslation;
  21214. const boxes = this.#boxes;
  21215. const quadPoints = new Float32Array(boxes.length * 8);
  21216. let i = 0;
  21217. for (const {
  21218. x,
  21219. y,
  21220. width,
  21221. height
  21222. } of boxes) {
  21223. const sx = x * pageWidth + pageX;
  21224. const sy = (1 - y - height) * pageHeight + pageY;
  21225. quadPoints[i] = quadPoints[i + 4] = sx;
  21226. quadPoints[i + 1] = quadPoints[i + 3] = sy;
  21227. quadPoints[i + 2] = quadPoints[i + 6] = sx + width * pageWidth;
  21228. quadPoints[i + 5] = quadPoints[i + 7] = sy + height * pageHeight;
  21229. i += 8;
  21230. }
  21231. return quadPoints;
  21232. }
  21233. #serializeOutlines(rect) {
  21234. return this.#highlightOutlines.serialize(rect, this.#getRotation());
  21235. }
  21236. static startHighlighting(parent, isLTR, {
  21237. target: textLayer,
  21238. x,
  21239. y
  21240. }) {
  21241. const {
  21242. x: layerX,
  21243. y: layerY,
  21244. width: parentWidth,
  21245. height: parentHeight
  21246. } = textLayer.getBoundingClientRect();
  21247. const ac = new AbortController();
  21248. const signal = parent.combinedSignal(ac);
  21249. const pointerDown = e => {
  21250. e.preventDefault();
  21251. e.stopPropagation();
  21252. };
  21253. const pointerUpCallback = e => {
  21254. ac.abort();
  21255. this.#endHighlight(parent, e);
  21256. };
  21257. window.addEventListener("blur", pointerUpCallback, {
  21258. signal
  21259. });
  21260. window.addEventListener("pointerup", pointerUpCallback, {
  21261. signal
  21262. });
  21263. window.addEventListener("pointerdown", pointerDown, {
  21264. capture: true,
  21265. passive: false,
  21266. signal
  21267. });
  21268. window.addEventListener("contextmenu", noContextMenu, {
  21269. signal
  21270. });
  21271. textLayer.addEventListener("pointermove", this.#highlightMove.bind(this, parent), {
  21272. signal
  21273. });
  21274. this._freeHighlight = new FreeOutliner({
  21275. x,
  21276. y
  21277. }, [layerX, layerY, parentWidth, parentHeight], parent.scale, this._defaultThickness / 2, isLTR, 0.001);
  21278. ({
  21279. id: this._freeHighlightId,
  21280. clipPathId: this._freeHighlightClipId
  21281. } = parent.drawLayer.highlight(this._freeHighlight, this._defaultColor, this._defaultOpacity, true));
  21282. }
  21283. static #highlightMove(parent, event) {
  21284. if (this._freeHighlight.add(event)) {
  21285. parent.drawLayer.updatePath(this._freeHighlightId, this._freeHighlight);
  21286. }
  21287. }
  21288. static #endHighlight(parent, event) {
  21289. if (!this._freeHighlight.isEmpty()) {
  21290. parent.createAndAddNewEditor(event, false, {
  21291. highlightId: this._freeHighlightId,
  21292. highlightOutlines: this._freeHighlight.getOutlines(),
  21293. clipPathId: this._freeHighlightClipId,
  21294. methodOfCreation: "main_toolbar"
  21295. });
  21296. } else {
  21297. parent.drawLayer.removeFreeHighlight(this._freeHighlightId);
  21298. }
  21299. this._freeHighlightId = -1;
  21300. this._freeHighlight = null;
  21301. this._freeHighlightClipId = "";
  21302. }
  21303. static async deserialize(data, parent, uiManager) {
  21304. let initialData = null;
  21305. if (data instanceof HighlightAnnotationElement) {
  21306. const {
  21307. data: {
  21308. quadPoints,
  21309. rect,
  21310. rotation,
  21311. id,
  21312. color,
  21313. opacity,
  21314. popupRef
  21315. },
  21316. parent: {
  21317. page: {
  21318. pageNumber
  21319. }
  21320. }
  21321. } = data;
  21322. initialData = data = {
  21323. annotationType: AnnotationEditorType.HIGHLIGHT,
  21324. color: Array.from(color),
  21325. opacity,
  21326. quadPoints,
  21327. boxes: null,
  21328. pageIndex: pageNumber - 1,
  21329. rect: rect.slice(0),
  21330. rotation,
  21331. id,
  21332. deleted: false,
  21333. popupRef
  21334. };
  21335. } else if (data instanceof InkAnnotationElement) {
  21336. const {
  21337. data: {
  21338. inkLists,
  21339. rect,
  21340. rotation,
  21341. id,
  21342. color,
  21343. borderStyle: {
  21344. rawWidth: thickness
  21345. },
  21346. popupRef
  21347. },
  21348. parent: {
  21349. page: {
  21350. pageNumber
  21351. }
  21352. }
  21353. } = data;
  21354. initialData = data = {
  21355. annotationType: AnnotationEditorType.HIGHLIGHT,
  21356. color: Array.from(color),
  21357. thickness,
  21358. inkLists,
  21359. boxes: null,
  21360. pageIndex: pageNumber - 1,
  21361. rect: rect.slice(0),
  21362. rotation,
  21363. id,
  21364. deleted: false,
  21365. popupRef
  21366. };
  21367. }
  21368. const {
  21369. color,
  21370. quadPoints,
  21371. inkLists,
  21372. opacity
  21373. } = data;
  21374. const editor = await super.deserialize(data, parent, uiManager);
  21375. editor.color = Util.makeHexColor(...color);
  21376. editor.#opacity = opacity || 1;
  21377. if (inkLists) {
  21378. editor.#thickness = data.thickness;
  21379. }
  21380. editor.annotationElementId = data.id || null;
  21381. editor._initialData = initialData;
  21382. const [pageWidth, pageHeight] = editor.pageDimensions;
  21383. const [pageX, pageY] = editor.pageTranslation;
  21384. if (quadPoints) {
  21385. const boxes = editor.#boxes = [];
  21386. for (let i = 0; i < quadPoints.length; i += 8) {
  21387. boxes.push({
  21388. x: (quadPoints[i] - pageX) / pageWidth,
  21389. y: 1 - (quadPoints[i + 1] - pageY) / pageHeight,
  21390. width: (quadPoints[i + 2] - quadPoints[i]) / pageWidth,
  21391. height: (quadPoints[i + 1] - quadPoints[i + 5]) / pageHeight
  21392. });
  21393. }
  21394. editor.#createOutlines();
  21395. editor.#addToDrawLayer();
  21396. editor.rotate(editor.rotation);
  21397. } else if (inkLists) {
  21398. editor.#isFreeHighlight = true;
  21399. const points = inkLists[0];
  21400. const point = {
  21401. x: points[0] - pageX,
  21402. y: pageHeight - (points[1] - pageY)
  21403. };
  21404. const outliner = new FreeOutliner(point, [0, 0, pageWidth, pageHeight], 1, editor.#thickness / 2, true, 0.001);
  21405. for (let i = 0, ii = points.length; i < ii; i += 2) {
  21406. point.x = points[i] - pageX;
  21407. point.y = pageHeight - (points[i + 1] - pageY);
  21408. outliner.add(point);
  21409. }
  21410. const {
  21411. id,
  21412. clipPathId
  21413. } = parent.drawLayer.highlight(outliner, editor.color, editor._defaultOpacity, true);
  21414. editor.#createFreeOutlines({
  21415. highlightOutlines: outliner.getOutlines(),
  21416. highlightId: id,
  21417. clipPathId
  21418. });
  21419. editor.#addToDrawLayer();
  21420. }
  21421. return editor;
  21422. }
  21423. serialize(isForCopying = false) {
  21424. if (this.isEmpty() || isForCopying) {
  21425. return null;
  21426. }
  21427. if (this.deleted) {
  21428. return this.serializeDeleted();
  21429. }
  21430. const rect = this.getRect(0, 0);
  21431. const color = AnnotationEditor._colorManager.convert(this.color);
  21432. const serialized = {
  21433. annotationType: AnnotationEditorType.HIGHLIGHT,
  21434. color,
  21435. opacity: this.#opacity,
  21436. thickness: this.#thickness,
  21437. quadPoints: this.#serializeBoxes(),
  21438. outlines: this.#serializeOutlines(rect),
  21439. pageIndex: this.pageIndex,
  21440. rect,
  21441. rotation: this.#getRotation(),
  21442. structTreeParentId: this._structTreeParentId
  21443. };
  21444. if (this.annotationElementId && !this.#hasElementChanged(serialized)) {
  21445. return null;
  21446. }
  21447. serialized.id = this.annotationElementId;
  21448. return serialized;
  21449. }
  21450. #hasElementChanged(serialized) {
  21451. const {
  21452. color
  21453. } = this._initialData;
  21454. return serialized.color.some((c, i) => c !== color[i]);
  21455. }
  21456. renderAnnotationElement(annotation) {
  21457. annotation.updateEdited({
  21458. rect: this.getRect(0, 0)
  21459. });
  21460. return null;
  21461. }
  21462. static canCreateNewEmptyEditor() {
  21463. return false;
  21464. }
  21465. }
  21466. ;// ./src/display/editor/ink.js
  21467. class InkEditor extends AnnotationEditor {
  21468. #baseHeight = 0;
  21469. #baseWidth = 0;
  21470. #canvasContextMenuTimeoutId = null;
  21471. #currentPath2D = new Path2D();
  21472. #disableEditing = false;
  21473. #drawingAC = null;
  21474. #hasSomethingToDraw = false;
  21475. #isCanvasInitialized = false;
  21476. #observer = null;
  21477. #pointerdownAC = null;
  21478. #realWidth = 0;
  21479. #realHeight = 0;
  21480. #requestFrameCallback = null;
  21481. static _defaultColor = null;
  21482. static _defaultOpacity = 1;
  21483. static _defaultThickness = 1;
  21484. static _type = "ink";
  21485. static _editorType = AnnotationEditorType.INK;
  21486. constructor(params) {
  21487. super({
  21488. ...params,
  21489. name: "inkEditor"
  21490. });
  21491. this.color = params.color || null;
  21492. this.thickness = params.thickness || null;
  21493. this.opacity = params.opacity || null;
  21494. this.paths = [];
  21495. this.bezierPath2D = [];
  21496. this.allRawPaths = [];
  21497. this.currentPath = [];
  21498. this.scaleFactor = 1;
  21499. this.translationX = this.translationY = 0;
  21500. this.x = 0;
  21501. this.y = 0;
  21502. this._willKeepAspectRatio = true;
  21503. }
  21504. static initialize(l10n, uiManager) {
  21505. AnnotationEditor.initialize(l10n, uiManager);
  21506. }
  21507. static updateDefaultParams(type, value) {
  21508. switch (type) {
  21509. case AnnotationEditorParamsType.INK_THICKNESS:
  21510. InkEditor._defaultThickness = value;
  21511. break;
  21512. case AnnotationEditorParamsType.INK_COLOR:
  21513. InkEditor._defaultColor = value;
  21514. break;
  21515. case AnnotationEditorParamsType.INK_OPACITY:
  21516. InkEditor._defaultOpacity = value / 100;
  21517. break;
  21518. }
  21519. }
  21520. updateParams(type, value) {
  21521. switch (type) {
  21522. case AnnotationEditorParamsType.INK_THICKNESS:
  21523. this.#updateThickness(value);
  21524. break;
  21525. case AnnotationEditorParamsType.INK_COLOR:
  21526. this.#updateColor(value);
  21527. break;
  21528. case AnnotationEditorParamsType.INK_OPACITY:
  21529. this.#updateOpacity(value);
  21530. break;
  21531. }
  21532. }
  21533. static get defaultPropertiesToUpdate() {
  21534. return [[AnnotationEditorParamsType.INK_THICKNESS, InkEditor._defaultThickness], [AnnotationEditorParamsType.INK_COLOR, InkEditor._defaultColor || AnnotationEditor._defaultLineColor], [AnnotationEditorParamsType.INK_OPACITY, Math.round(InkEditor._defaultOpacity * 100)]];
  21535. }
  21536. get propertiesToUpdate() {
  21537. return [[AnnotationEditorParamsType.INK_THICKNESS, this.thickness || InkEditor._defaultThickness], [AnnotationEditorParamsType.INK_COLOR, this.color || InkEditor._defaultColor || AnnotationEditor._defaultLineColor], [AnnotationEditorParamsType.INK_OPACITY, Math.round(100 * (this.opacity ?? InkEditor._defaultOpacity))]];
  21538. }
  21539. #updateThickness(thickness) {
  21540. const setThickness = th => {
  21541. this.thickness = th;
  21542. this.#fitToContent();
  21543. };
  21544. const savedThickness = this.thickness;
  21545. this.addCommands({
  21546. cmd: setThickness.bind(this, thickness),
  21547. undo: setThickness.bind(this, savedThickness),
  21548. post: this._uiManager.updateUI.bind(this._uiManager, this),
  21549. mustExec: true,
  21550. type: AnnotationEditorParamsType.INK_THICKNESS,
  21551. overwriteIfSameType: true,
  21552. keepUndo: true
  21553. });
  21554. }
  21555. #updateColor(color) {
  21556. const setColor = col => {
  21557. this.color = col;
  21558. this.#redraw();
  21559. };
  21560. const savedColor = this.color;
  21561. this.addCommands({
  21562. cmd: setColor.bind(this, color),
  21563. undo: setColor.bind(this, savedColor),
  21564. post: this._uiManager.updateUI.bind(this._uiManager, this),
  21565. mustExec: true,
  21566. type: AnnotationEditorParamsType.INK_COLOR,
  21567. overwriteIfSameType: true,
  21568. keepUndo: true
  21569. });
  21570. }
  21571. #updateOpacity(opacity) {
  21572. const setOpacity = op => {
  21573. this.opacity = op;
  21574. this.#redraw();
  21575. };
  21576. opacity /= 100;
  21577. const savedOpacity = this.opacity;
  21578. this.addCommands({
  21579. cmd: setOpacity.bind(this, opacity),
  21580. undo: setOpacity.bind(this, savedOpacity),
  21581. post: this._uiManager.updateUI.bind(this._uiManager, this),
  21582. mustExec: true,
  21583. type: AnnotationEditorParamsType.INK_OPACITY,
  21584. overwriteIfSameType: true,
  21585. keepUndo: true
  21586. });
  21587. }
  21588. rebuild() {
  21589. if (!this.parent) {
  21590. return;
  21591. }
  21592. super.rebuild();
  21593. if (this.div === null) {
  21594. return;
  21595. }
  21596. if (!this.canvas) {
  21597. this.#createCanvas();
  21598. this.#createObserver();
  21599. }
  21600. if (!this.isAttachedToDOM) {
  21601. this.parent.add(this);
  21602. this.#setCanvasDims();
  21603. }
  21604. this.#fitToContent();
  21605. }
  21606. remove() {
  21607. if (this.canvas === null) {
  21608. return;
  21609. }
  21610. if (!this.isEmpty()) {
  21611. this.commit();
  21612. }
  21613. this.canvas.width = this.canvas.height = 0;
  21614. this.canvas.remove();
  21615. this.canvas = null;
  21616. if (this.#canvasContextMenuTimeoutId) {
  21617. clearTimeout(this.#canvasContextMenuTimeoutId);
  21618. this.#canvasContextMenuTimeoutId = null;
  21619. }
  21620. this.#observer?.disconnect();
  21621. this.#observer = null;
  21622. super.remove();
  21623. }
  21624. setParent(parent) {
  21625. if (!this.parent && parent) {
  21626. this._uiManager.removeShouldRescale(this);
  21627. } else if (this.parent && parent === null) {
  21628. this._uiManager.addShouldRescale(this);
  21629. }
  21630. super.setParent(parent);
  21631. }
  21632. onScaleChanging() {
  21633. const [parentWidth, parentHeight] = this.parentDimensions;
  21634. const width = this.width * parentWidth;
  21635. const height = this.height * parentHeight;
  21636. this.setDimensions(width, height);
  21637. }
  21638. enableEditMode() {
  21639. if (this.#disableEditing || this.canvas === null) {
  21640. return;
  21641. }
  21642. super.enableEditMode();
  21643. this._isDraggable = false;
  21644. this.#addPointerdownListener();
  21645. }
  21646. disableEditMode() {
  21647. if (!this.isInEditMode() || this.canvas === null) {
  21648. return;
  21649. }
  21650. super.disableEditMode();
  21651. this._isDraggable = !this.isEmpty();
  21652. this.div.classList.remove("editing");
  21653. this.#removePointerdownListener();
  21654. }
  21655. onceAdded() {
  21656. this._isDraggable = !this.isEmpty();
  21657. }
  21658. isEmpty() {
  21659. return this.paths.length === 0 || this.paths.length === 1 && this.paths[0].length === 0;
  21660. }
  21661. #getInitialBBox() {
  21662. const {
  21663. parentRotation,
  21664. parentDimensions: [width, height]
  21665. } = this;
  21666. switch (parentRotation) {
  21667. case 90:
  21668. return [0, height, height, width];
  21669. case 180:
  21670. return [width, height, width, height];
  21671. case 270:
  21672. return [width, 0, height, width];
  21673. default:
  21674. return [0, 0, width, height];
  21675. }
  21676. }
  21677. #setStroke() {
  21678. const {
  21679. ctx,
  21680. color,
  21681. opacity,
  21682. thickness,
  21683. parentScale,
  21684. scaleFactor
  21685. } = this;
  21686. ctx.lineWidth = thickness * parentScale / scaleFactor;
  21687. ctx.lineCap = "round";
  21688. ctx.lineJoin = "round";
  21689. ctx.miterLimit = 10;
  21690. ctx.strokeStyle = `${color}${opacityToHex(opacity)}`;
  21691. }
  21692. #startDrawing(x, y) {
  21693. this.canvas.addEventListener("contextmenu", noContextMenu, {
  21694. signal: this._uiManager._signal
  21695. });
  21696. this.#removePointerdownListener();
  21697. this.#drawingAC = new AbortController();
  21698. const signal = this._uiManager.combinedSignal(this.#drawingAC);
  21699. this.canvas.addEventListener("pointerleave", this.canvasPointerleave.bind(this), {
  21700. signal
  21701. });
  21702. this.canvas.addEventListener("pointermove", this.canvasPointermove.bind(this), {
  21703. signal
  21704. });
  21705. this.canvas.addEventListener("pointerup", this.canvasPointerup.bind(this), {
  21706. signal
  21707. });
  21708. this.isEditing = true;
  21709. if (!this.#isCanvasInitialized) {
  21710. this.#isCanvasInitialized = true;
  21711. this.#setCanvasDims();
  21712. this.thickness ||= InkEditor._defaultThickness;
  21713. this.color ||= InkEditor._defaultColor || AnnotationEditor._defaultLineColor;
  21714. this.opacity ??= InkEditor._defaultOpacity;
  21715. }
  21716. this.currentPath.push([x, y]);
  21717. this.#hasSomethingToDraw = false;
  21718. this.#setStroke();
  21719. this.#requestFrameCallback = () => {
  21720. this.#drawPoints();
  21721. if (this.#requestFrameCallback) {
  21722. window.requestAnimationFrame(this.#requestFrameCallback);
  21723. }
  21724. };
  21725. window.requestAnimationFrame(this.#requestFrameCallback);
  21726. }
  21727. #draw(x, y) {
  21728. const [lastX, lastY] = this.currentPath.at(-1);
  21729. if (this.currentPath.length > 1 && x === lastX && y === lastY) {
  21730. return;
  21731. }
  21732. const currentPath = this.currentPath;
  21733. let path2D = this.#currentPath2D;
  21734. currentPath.push([x, y]);
  21735. this.#hasSomethingToDraw = true;
  21736. if (currentPath.length <= 2) {
  21737. path2D.moveTo(...currentPath[0]);
  21738. path2D.lineTo(x, y);
  21739. return;
  21740. }
  21741. if (currentPath.length === 3) {
  21742. this.#currentPath2D = path2D = new Path2D();
  21743. path2D.moveTo(...currentPath[0]);
  21744. }
  21745. this.#makeBezierCurve(path2D, ...currentPath.at(-3), ...currentPath.at(-2), x, y);
  21746. }
  21747. #endPath() {
  21748. if (this.currentPath.length === 0) {
  21749. return;
  21750. }
  21751. const lastPoint = this.currentPath.at(-1);
  21752. this.#currentPath2D.lineTo(...lastPoint);
  21753. }
  21754. #stopDrawing(x, y) {
  21755. this.#requestFrameCallback = null;
  21756. x = Math.min(Math.max(x, 0), this.canvas.width);
  21757. y = Math.min(Math.max(y, 0), this.canvas.height);
  21758. this.#draw(x, y);
  21759. this.#endPath();
  21760. let bezier;
  21761. if (this.currentPath.length !== 1) {
  21762. bezier = this.#generateBezierPoints();
  21763. } else {
  21764. const xy = [x, y];
  21765. bezier = [[xy, xy.slice(), xy.slice(), xy]];
  21766. }
  21767. const path2D = this.#currentPath2D;
  21768. const currentPath = this.currentPath;
  21769. this.currentPath = [];
  21770. this.#currentPath2D = new Path2D();
  21771. const cmd = () => {
  21772. this.allRawPaths.push(currentPath);
  21773. this.paths.push(bezier);
  21774. this.bezierPath2D.push(path2D);
  21775. this._uiManager.rebuild(this);
  21776. };
  21777. const undo = () => {
  21778. this.allRawPaths.pop();
  21779. this.paths.pop();
  21780. this.bezierPath2D.pop();
  21781. if (this.paths.length === 0) {
  21782. this.remove();
  21783. } else {
  21784. if (!this.canvas) {
  21785. this.#createCanvas();
  21786. this.#createObserver();
  21787. }
  21788. this.#fitToContent();
  21789. }
  21790. };
  21791. this.addCommands({
  21792. cmd,
  21793. undo,
  21794. mustExec: true
  21795. });
  21796. }
  21797. #drawPoints() {
  21798. if (!this.#hasSomethingToDraw) {
  21799. return;
  21800. }
  21801. this.#hasSomethingToDraw = false;
  21802. const thickness = Math.ceil(this.thickness * this.parentScale);
  21803. const lastPoints = this.currentPath.slice(-3);
  21804. const x = lastPoints.map(xy => xy[0]);
  21805. const y = lastPoints.map(xy => xy[1]);
  21806. const xMin = Math.min(...x) - thickness;
  21807. const xMax = Math.max(...x) + thickness;
  21808. const yMin = Math.min(...y) - thickness;
  21809. const yMax = Math.max(...y) + thickness;
  21810. const {
  21811. ctx
  21812. } = this;
  21813. ctx.save();
  21814. ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  21815. for (const path of this.bezierPath2D) {
  21816. ctx.stroke(path);
  21817. }
  21818. ctx.stroke(this.#currentPath2D);
  21819. ctx.restore();
  21820. }
  21821. #makeBezierCurve(path2D, x0, y0, x1, y1, x2, y2) {
  21822. const prevX = (x0 + x1) / 2;
  21823. const prevY = (y0 + y1) / 2;
  21824. const x3 = (x1 + x2) / 2;
  21825. const y3 = (y1 + y2) / 2;
  21826. path2D.bezierCurveTo(prevX + 2 * (x1 - prevX) / 3, prevY + 2 * (y1 - prevY) / 3, x3 + 2 * (x1 - x3) / 3, y3 + 2 * (y1 - y3) / 3, x3, y3);
  21827. }
  21828. #generateBezierPoints() {
  21829. const path = this.currentPath;
  21830. if (path.length <= 2) {
  21831. return [[path[0], path[0], path.at(-1), path.at(-1)]];
  21832. }
  21833. const bezierPoints = [];
  21834. let i;
  21835. let [x0, y0] = path[0];
  21836. for (i = 1; i < path.length - 2; i++) {
  21837. const [x1, y1] = path[i];
  21838. const [x2, y2] = path[i + 1];
  21839. const x3 = (x1 + x2) / 2;
  21840. const y3 = (y1 + y2) / 2;
  21841. const control1 = [x0 + 2 * (x1 - x0) / 3, y0 + 2 * (y1 - y0) / 3];
  21842. const control2 = [x3 + 2 * (x1 - x3) / 3, y3 + 2 * (y1 - y3) / 3];
  21843. bezierPoints.push([[x0, y0], control1, control2, [x3, y3]]);
  21844. [x0, y0] = [x3, y3];
  21845. }
  21846. const [x1, y1] = path[i];
  21847. const [x2, y2] = path[i + 1];
  21848. const control1 = [x0 + 2 * (x1 - x0) / 3, y0 + 2 * (y1 - y0) / 3];
  21849. const control2 = [x2 + 2 * (x1 - x2) / 3, y2 + 2 * (y1 - y2) / 3];
  21850. bezierPoints.push([[x0, y0], control1, control2, [x2, y2]]);
  21851. return bezierPoints;
  21852. }
  21853. #redraw() {
  21854. if (this.isEmpty()) {
  21855. this.#updateTransform();
  21856. return;
  21857. }
  21858. this.#setStroke();
  21859. const {
  21860. canvas,
  21861. ctx
  21862. } = this;
  21863. ctx.setTransform(1, 0, 0, 1, 0, 0);
  21864. ctx.clearRect(0, 0, canvas.width, canvas.height);
  21865. this.#updateTransform();
  21866. for (const path of this.bezierPath2D) {
  21867. ctx.stroke(path);
  21868. }
  21869. }
  21870. commit() {
  21871. if (this.#disableEditing) {
  21872. return;
  21873. }
  21874. super.commit();
  21875. this.isEditing = false;
  21876. this.disableEditMode();
  21877. this.setInForeground();
  21878. this.#disableEditing = true;
  21879. this.div.classList.add("disabled");
  21880. this.#fitToContent(true);
  21881. this.select();
  21882. this.parent.addInkEditorIfNeeded(true);
  21883. this.moveInDOM();
  21884. this.div.focus({
  21885. preventScroll: true
  21886. });
  21887. }
  21888. focusin(event) {
  21889. if (!this._focusEventsAllowed) {
  21890. return;
  21891. }
  21892. super.focusin(event);
  21893. this.enableEditMode();
  21894. }
  21895. #addPointerdownListener() {
  21896. if (this.#pointerdownAC) {
  21897. return;
  21898. }
  21899. this.#pointerdownAC = new AbortController();
  21900. const signal = this._uiManager.combinedSignal(this.#pointerdownAC);
  21901. this.canvas.addEventListener("pointerdown", this.canvasPointerdown.bind(this), {
  21902. signal
  21903. });
  21904. }
  21905. #removePointerdownListener() {
  21906. this.pointerdownAC?.abort();
  21907. this.pointerdownAC = null;
  21908. }
  21909. canvasPointerdown(event) {
  21910. if (event.button !== 0 || !this.isInEditMode() || this.#disableEditing) {
  21911. return;
  21912. }
  21913. this.setInForeground();
  21914. event.preventDefault();
  21915. if (!this.div.contains(document.activeElement)) {
  21916. this.div.focus({
  21917. preventScroll: true
  21918. });
  21919. }
  21920. this.#startDrawing(event.offsetX, event.offsetY);
  21921. }
  21922. canvasPointermove(event) {
  21923. event.preventDefault();
  21924. this.#draw(event.offsetX, event.offsetY);
  21925. }
  21926. canvasPointerup(event) {
  21927. event.preventDefault();
  21928. this.#endDrawing(event);
  21929. }
  21930. canvasPointerleave(event) {
  21931. this.#endDrawing(event);
  21932. }
  21933. #endDrawing(event) {
  21934. this.#drawingAC?.abort();
  21935. this.#drawingAC = null;
  21936. this.#addPointerdownListener();
  21937. if (this.#canvasContextMenuTimeoutId) {
  21938. clearTimeout(this.#canvasContextMenuTimeoutId);
  21939. }
  21940. this.#canvasContextMenuTimeoutId = setTimeout(() => {
  21941. this.#canvasContextMenuTimeoutId = null;
  21942. this.canvas.removeEventListener("contextmenu", noContextMenu);
  21943. }, 10);
  21944. this.#stopDrawing(event.offsetX, event.offsetY);
  21945. this.addToAnnotationStorage();
  21946. this.setInBackground();
  21947. }
  21948. #createCanvas() {
  21949. this.canvas = document.createElement("canvas");
  21950. this.canvas.width = this.canvas.height = 0;
  21951. this.canvas.className = "inkEditorCanvas";
  21952. this.canvas.setAttribute("data-l10n-id", "pdfjs-ink-canvas");
  21953. this.div.append(this.canvas);
  21954. this.ctx = this.canvas.getContext("2d");
  21955. }
  21956. #createObserver() {
  21957. this.#observer = new ResizeObserver(entries => {
  21958. const rect = entries[0].contentRect;
  21959. if (rect.width && rect.height) {
  21960. this.setDimensions(rect.width, rect.height);
  21961. }
  21962. });
  21963. this.#observer.observe(this.div);
  21964. this._uiManager._signal.addEventListener("abort", () => {
  21965. this.#observer?.disconnect();
  21966. this.#observer = null;
  21967. }, {
  21968. once: true
  21969. });
  21970. }
  21971. get isResizable() {
  21972. return !this.isEmpty() && this.#disableEditing;
  21973. }
  21974. render() {
  21975. if (this.div) {
  21976. return this.div;
  21977. }
  21978. let baseX, baseY;
  21979. if (this.width) {
  21980. baseX = this.x;
  21981. baseY = this.y;
  21982. }
  21983. super.render();
  21984. this.div.setAttribute("data-l10n-id", "pdfjs-ink");
  21985. const [x, y, w, h] = this.#getInitialBBox();
  21986. this.setAt(x, y, 0, 0);
  21987. this.setDims(w, h);
  21988. this.#createCanvas();
  21989. if (this.width) {
  21990. const [parentWidth, parentHeight] = this.parentDimensions;
  21991. this.setAspectRatio(this.width * parentWidth, this.height * parentHeight);
  21992. this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
  21993. this.#isCanvasInitialized = true;
  21994. this.#setCanvasDims();
  21995. this.setDims(this.width * parentWidth, this.height * parentHeight);
  21996. this.#redraw();
  21997. this.div.classList.add("disabled");
  21998. } else {
  21999. this.div.classList.add("editing");
  22000. this.enableEditMode();
  22001. }
  22002. this.#createObserver();
  22003. return this.div;
  22004. }
  22005. #setCanvasDims() {
  22006. if (!this.#isCanvasInitialized) {
  22007. return;
  22008. }
  22009. const [parentWidth, parentHeight] = this.parentDimensions;
  22010. this.canvas.width = Math.ceil(this.width * parentWidth);
  22011. this.canvas.height = Math.ceil(this.height * parentHeight);
  22012. this.#updateTransform();
  22013. }
  22014. setDimensions(width, height) {
  22015. const roundedWidth = Math.round(width);
  22016. const roundedHeight = Math.round(height);
  22017. if (this.#realWidth === roundedWidth && this.#realHeight === roundedHeight) {
  22018. return;
  22019. }
  22020. this.#realWidth = roundedWidth;
  22021. this.#realHeight = roundedHeight;
  22022. this.canvas.style.visibility = "hidden";
  22023. const [parentWidth, parentHeight] = this.parentDimensions;
  22024. this.width = width / parentWidth;
  22025. this.height = height / parentHeight;
  22026. this.fixAndSetPosition();
  22027. if (this.#disableEditing) {
  22028. this.#setScaleFactor(width, height);
  22029. }
  22030. this.#setCanvasDims();
  22031. this.#redraw();
  22032. this.canvas.style.visibility = "visible";
  22033. this.fixDims();
  22034. }
  22035. #setScaleFactor(width, height) {
  22036. const padding = this.#getPadding();
  22037. const scaleFactorW = (width - padding) / this.#baseWidth;
  22038. const scaleFactorH = (height - padding) / this.#baseHeight;
  22039. this.scaleFactor = Math.min(scaleFactorW, scaleFactorH);
  22040. }
  22041. #updateTransform() {
  22042. const padding = this.#getPadding() / 2;
  22043. this.ctx.setTransform(this.scaleFactor, 0, 0, this.scaleFactor, this.translationX * this.scaleFactor + padding, this.translationY * this.scaleFactor + padding);
  22044. }
  22045. static #buildPath2D(bezier) {
  22046. const path2D = new Path2D();
  22047. for (let i = 0, ii = bezier.length; i < ii; i++) {
  22048. const [first, control1, control2, second] = bezier[i];
  22049. if (i === 0) {
  22050. path2D.moveTo(...first);
  22051. }
  22052. path2D.bezierCurveTo(control1[0], control1[1], control2[0], control2[1], second[0], second[1]);
  22053. }
  22054. return path2D;
  22055. }
  22056. static #toPDFCoordinates(points, rect, rotation) {
  22057. const [blX, blY, trX, trY] = rect;
  22058. switch (rotation) {
  22059. case 0:
  22060. for (let i = 0, ii = points.length; i < ii; i += 2) {
  22061. points[i] += blX;
  22062. points[i + 1] = trY - points[i + 1];
  22063. }
  22064. break;
  22065. case 90:
  22066. for (let i = 0, ii = points.length; i < ii; i += 2) {
  22067. const x = points[i];
  22068. points[i] = points[i + 1] + blX;
  22069. points[i + 1] = x + blY;
  22070. }
  22071. break;
  22072. case 180:
  22073. for (let i = 0, ii = points.length; i < ii; i += 2) {
  22074. points[i] = trX - points[i];
  22075. points[i + 1] += blY;
  22076. }
  22077. break;
  22078. case 270:
  22079. for (let i = 0, ii = points.length; i < ii; i += 2) {
  22080. const x = points[i];
  22081. points[i] = trX - points[i + 1];
  22082. points[i + 1] = trY - x;
  22083. }
  22084. break;
  22085. default:
  22086. throw new Error("Invalid rotation");
  22087. }
  22088. return points;
  22089. }
  22090. static #fromPDFCoordinates(points, rect, rotation) {
  22091. const [blX, blY, trX, trY] = rect;
  22092. switch (rotation) {
  22093. case 0:
  22094. for (let i = 0, ii = points.length; i < ii; i += 2) {
  22095. points[i] -= blX;
  22096. points[i + 1] = trY - points[i + 1];
  22097. }
  22098. break;
  22099. case 90:
  22100. for (let i = 0, ii = points.length; i < ii; i += 2) {
  22101. const x = points[i];
  22102. points[i] = points[i + 1] - blY;
  22103. points[i + 1] = x - blX;
  22104. }
  22105. break;
  22106. case 180:
  22107. for (let i = 0, ii = points.length; i < ii; i += 2) {
  22108. points[i] = trX - points[i];
  22109. points[i + 1] -= blY;
  22110. }
  22111. break;
  22112. case 270:
  22113. for (let i = 0, ii = points.length; i < ii; i += 2) {
  22114. const x = points[i];
  22115. points[i] = trY - points[i + 1];
  22116. points[i + 1] = trX - x;
  22117. }
  22118. break;
  22119. default:
  22120. throw new Error("Invalid rotation");
  22121. }
  22122. return points;
  22123. }
  22124. #serializePaths(s, tx, ty, rect) {
  22125. const paths = [];
  22126. const padding = this.thickness / 2;
  22127. const shiftX = s * tx + padding;
  22128. const shiftY = s * ty + padding;
  22129. for (const bezier of this.paths) {
  22130. const buffer = [];
  22131. const points = [];
  22132. for (let j = 0, jj = bezier.length; j < jj; j++) {
  22133. const [first, control1, control2, second] = bezier[j];
  22134. if (first[0] === second[0] && first[1] === second[1] && jj === 1) {
  22135. const p0 = s * first[0] + shiftX;
  22136. const p1 = s * first[1] + shiftY;
  22137. buffer.push(p0, p1);
  22138. points.push(p0, p1);
  22139. break;
  22140. }
  22141. const p10 = s * first[0] + shiftX;
  22142. const p11 = s * first[1] + shiftY;
  22143. const p20 = s * control1[0] + shiftX;
  22144. const p21 = s * control1[1] + shiftY;
  22145. const p30 = s * control2[0] + shiftX;
  22146. const p31 = s * control2[1] + shiftY;
  22147. const p40 = s * second[0] + shiftX;
  22148. const p41 = s * second[1] + shiftY;
  22149. if (j === 0) {
  22150. buffer.push(p10, p11);
  22151. points.push(p10, p11);
  22152. }
  22153. buffer.push(p20, p21, p30, p31, p40, p41);
  22154. points.push(p20, p21);
  22155. if (j === jj - 1) {
  22156. points.push(p40, p41);
  22157. }
  22158. }
  22159. paths.push({
  22160. bezier: InkEditor.#toPDFCoordinates(buffer, rect, this.rotation),
  22161. points: InkEditor.#toPDFCoordinates(points, rect, this.rotation)
  22162. });
  22163. }
  22164. return paths;
  22165. }
  22166. #getBbox() {
  22167. let xMin = Infinity;
  22168. let xMax = -Infinity;
  22169. let yMin = Infinity;
  22170. let yMax = -Infinity;
  22171. for (const path of this.paths) {
  22172. for (const [first, control1, control2, second] of path) {
  22173. const bbox = Util.bezierBoundingBox(...first, ...control1, ...control2, ...second);
  22174. xMin = Math.min(xMin, bbox[0]);
  22175. yMin = Math.min(yMin, bbox[1]);
  22176. xMax = Math.max(xMax, bbox[2]);
  22177. yMax = Math.max(yMax, bbox[3]);
  22178. }
  22179. }
  22180. return [xMin, yMin, xMax, yMax];
  22181. }
  22182. #getPadding() {
  22183. return this.#disableEditing ? Math.ceil(this.thickness * this.parentScale) : 0;
  22184. }
  22185. #fitToContent(firstTime = false) {
  22186. if (this.isEmpty()) {
  22187. return;
  22188. }
  22189. if (!this.#disableEditing) {
  22190. this.#redraw();
  22191. return;
  22192. }
  22193. const bbox = this.#getBbox();
  22194. const padding = this.#getPadding();
  22195. this.#baseWidth = Math.max(AnnotationEditor.MIN_SIZE, bbox[2] - bbox[0]);
  22196. this.#baseHeight = Math.max(AnnotationEditor.MIN_SIZE, bbox[3] - bbox[1]);
  22197. const width = Math.ceil(padding + this.#baseWidth * this.scaleFactor);
  22198. const height = Math.ceil(padding + this.#baseHeight * this.scaleFactor);
  22199. const [parentWidth, parentHeight] = this.parentDimensions;
  22200. this.width = width / parentWidth;
  22201. this.height = height / parentHeight;
  22202. this.setAspectRatio(width, height);
  22203. const prevTranslationX = this.translationX;
  22204. const prevTranslationY = this.translationY;
  22205. this.translationX = -bbox[0];
  22206. this.translationY = -bbox[1];
  22207. this.#setCanvasDims();
  22208. this.#redraw();
  22209. this.#realWidth = width;
  22210. this.#realHeight = height;
  22211. this.setDims(width, height);
  22212. const unscaledPadding = firstTime ? padding / this.scaleFactor / 2 : 0;
  22213. this.translate(prevTranslationX - this.translationX - unscaledPadding, prevTranslationY - this.translationY - unscaledPadding);
  22214. }
  22215. static async deserialize(data, parent, uiManager) {
  22216. if (data instanceof InkAnnotationElement) {
  22217. return null;
  22218. }
  22219. const editor = await super.deserialize(data, parent, uiManager);
  22220. editor.thickness = data.thickness;
  22221. editor.color = Util.makeHexColor(...data.color);
  22222. editor.opacity = data.opacity;
  22223. const [pageWidth, pageHeight] = editor.pageDimensions;
  22224. const width = editor.width * pageWidth;
  22225. const height = editor.height * pageHeight;
  22226. const scaleFactor = editor.parentScale;
  22227. const padding = data.thickness / 2;
  22228. editor.#disableEditing = true;
  22229. editor.#realWidth = Math.round(width);
  22230. editor.#realHeight = Math.round(height);
  22231. const {
  22232. paths,
  22233. rect,
  22234. rotation
  22235. } = data;
  22236. for (let {
  22237. bezier
  22238. } of paths) {
  22239. bezier = InkEditor.#fromPDFCoordinates(bezier, rect, rotation);
  22240. const path = [];
  22241. editor.paths.push(path);
  22242. let p0 = scaleFactor * (bezier[0] - padding);
  22243. let p1 = scaleFactor * (bezier[1] - padding);
  22244. for (let i = 2, ii = bezier.length; i < ii; i += 6) {
  22245. const p10 = scaleFactor * (bezier[i] - padding);
  22246. const p11 = scaleFactor * (bezier[i + 1] - padding);
  22247. const p20 = scaleFactor * (bezier[i + 2] - padding);
  22248. const p21 = scaleFactor * (bezier[i + 3] - padding);
  22249. const p30 = scaleFactor * (bezier[i + 4] - padding);
  22250. const p31 = scaleFactor * (bezier[i + 5] - padding);
  22251. path.push([[p0, p1], [p10, p11], [p20, p21], [p30, p31]]);
  22252. p0 = p30;
  22253. p1 = p31;
  22254. }
  22255. const path2D = this.#buildPath2D(path);
  22256. editor.bezierPath2D.push(path2D);
  22257. }
  22258. const bbox = editor.#getBbox();
  22259. editor.#baseWidth = Math.max(AnnotationEditor.MIN_SIZE, bbox[2] - bbox[0]);
  22260. editor.#baseHeight = Math.max(AnnotationEditor.MIN_SIZE, bbox[3] - bbox[1]);
  22261. editor.#setScaleFactor(width, height);
  22262. return editor;
  22263. }
  22264. serialize() {
  22265. if (this.isEmpty()) {
  22266. return null;
  22267. }
  22268. const rect = this.getRect(0, 0);
  22269. const color = AnnotationEditor._colorManager.convert(this.ctx.strokeStyle);
  22270. return {
  22271. annotationType: AnnotationEditorType.INK,
  22272. color,
  22273. thickness: this.thickness,
  22274. opacity: this.opacity,
  22275. paths: this.#serializePaths(this.scaleFactor / this.parentScale, this.translationX, this.translationY, rect),
  22276. pageIndex: this.pageIndex,
  22277. rect,
  22278. rotation: this.rotation,
  22279. structTreeParentId: this._structTreeParentId
  22280. };
  22281. }
  22282. }
  22283. ;// ./src/display/editor/stamp.js
  22284. class StampEditor extends AnnotationEditor {
  22285. #bitmap = null;
  22286. #bitmapId = null;
  22287. #bitmapPromise = null;
  22288. #bitmapUrl = null;
  22289. #bitmapFile = null;
  22290. #bitmapFileName = "";
  22291. #canvas = null;
  22292. #observer = null;
  22293. #resizeTimeoutId = null;
  22294. #isSvg = false;
  22295. #hasBeenAddedInUndoStack = false;
  22296. static _type = "stamp";
  22297. static _editorType = AnnotationEditorType.STAMP;
  22298. constructor(params) {
  22299. super({
  22300. ...params,
  22301. name: "stampEditor"
  22302. });
  22303. this.#bitmapUrl = params.bitmapUrl;
  22304. this.#bitmapFile = params.bitmapFile;
  22305. }
  22306. static initialize(l10n, uiManager) {
  22307. AnnotationEditor.initialize(l10n, uiManager);
  22308. }
  22309. static get supportedTypes() {
  22310. const types = ["apng", "avif", "bmp", "gif", "jpeg", "png", "svg+xml", "webp", "x-icon"];
  22311. return shadow(this, "supportedTypes", types.map(type => `image/${type}`));
  22312. }
  22313. static get supportedTypesStr() {
  22314. return shadow(this, "supportedTypesStr", this.supportedTypes.join(","));
  22315. }
  22316. static isHandlingMimeForPasting(mime) {
  22317. return this.supportedTypes.includes(mime);
  22318. }
  22319. static paste(item, parent) {
  22320. parent.pasteEditor(AnnotationEditorType.STAMP, {
  22321. bitmapFile: item.getAsFile()
  22322. });
  22323. }
  22324. altTextFinish() {
  22325. if (this._uiManager.useNewAltTextFlow) {
  22326. this.div.hidden = false;
  22327. }
  22328. super.altTextFinish();
  22329. }
  22330. get telemetryFinalData() {
  22331. return {
  22332. type: "stamp",
  22333. hasAltText: !!this.altTextData?.altText
  22334. };
  22335. }
  22336. static computeTelemetryFinalData(data) {
  22337. const hasAltTextStats = data.get("hasAltText");
  22338. return {
  22339. hasAltText: hasAltTextStats.get(true) ?? 0,
  22340. hasNoAltText: hasAltTextStats.get(false) ?? 0
  22341. };
  22342. }
  22343. #getBitmapFetched(data, fromId = false) {
  22344. if (!data) {
  22345. this.remove();
  22346. return;
  22347. }
  22348. this.#bitmap = data.bitmap;
  22349. if (!fromId) {
  22350. this.#bitmapId = data.id;
  22351. this.#isSvg = data.isSvg;
  22352. }
  22353. if (data.file) {
  22354. this.#bitmapFileName = data.file.name;
  22355. }
  22356. this.#createCanvas();
  22357. }
  22358. #getBitmapDone() {
  22359. this.#bitmapPromise = null;
  22360. this._uiManager.enableWaiting(false);
  22361. if (!this.#canvas) {
  22362. return;
  22363. }
  22364. if (this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) {
  22365. this._editToolbar.hide();
  22366. this._uiManager.editAltText(this, true);
  22367. return;
  22368. }
  22369. if (!this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) {
  22370. this._reportTelemetry({
  22371. action: "pdfjs.image.image_added",
  22372. data: {
  22373. alt_text_modal: false,
  22374. alt_text_type: "empty"
  22375. }
  22376. });
  22377. try {
  22378. this.mlGuessAltText();
  22379. } catch {}
  22380. }
  22381. this.div.focus();
  22382. }
  22383. async mlGuessAltText(imageData = null, updateAltTextData = true) {
  22384. if (this.hasAltTextData()) {
  22385. return null;
  22386. }
  22387. const {
  22388. mlManager
  22389. } = this._uiManager;
  22390. if (!mlManager) {
  22391. throw new Error("No ML.");
  22392. }
  22393. if (!(await mlManager.isEnabledFor("altText"))) {
  22394. throw new Error("ML isn't enabled for alt text.");
  22395. }
  22396. const {
  22397. data,
  22398. width,
  22399. height
  22400. } = imageData || this.copyCanvas(null, null, true).imageData;
  22401. const response = await mlManager.guess({
  22402. name: "altText",
  22403. request: {
  22404. data,
  22405. width,
  22406. height,
  22407. channels: data.length / (width * height)
  22408. }
  22409. });
  22410. if (!response) {
  22411. throw new Error("No response from the AI service.");
  22412. }
  22413. if (response.error) {
  22414. throw new Error("Error from the AI service.");
  22415. }
  22416. if (response.cancel) {
  22417. return null;
  22418. }
  22419. if (!response.output) {
  22420. throw new Error("No valid response from the AI service.");
  22421. }
  22422. const altText = response.output;
  22423. await this.setGuessedAltText(altText);
  22424. if (updateAltTextData && !this.hasAltTextData()) {
  22425. this.altTextData = {
  22426. alt: altText,
  22427. decorative: false
  22428. };
  22429. }
  22430. return altText;
  22431. }
  22432. #getBitmap() {
  22433. if (this.#bitmapId) {
  22434. this._uiManager.enableWaiting(true);
  22435. this._uiManager.imageManager.getFromId(this.#bitmapId).then(data => this.#getBitmapFetched(data, true)).finally(() => this.#getBitmapDone());
  22436. return;
  22437. }
  22438. if (this.#bitmapUrl) {
  22439. const url = this.#bitmapUrl;
  22440. this.#bitmapUrl = null;
  22441. this._uiManager.enableWaiting(true);
  22442. this.#bitmapPromise = this._uiManager.imageManager.getFromUrl(url).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone());
  22443. return;
  22444. }
  22445. if (this.#bitmapFile) {
  22446. const file = this.#bitmapFile;
  22447. this.#bitmapFile = null;
  22448. this._uiManager.enableWaiting(true);
  22449. this.#bitmapPromise = this._uiManager.imageManager.getFromFile(file).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone());
  22450. return;
  22451. }
  22452. const input = document.createElement("input");
  22453. input.type = "file";
  22454. input.accept = StampEditor.supportedTypesStr;
  22455. const signal = this._uiManager._signal;
  22456. this.#bitmapPromise = new Promise(resolve => {
  22457. input.addEventListener("change", async () => {
  22458. if (!input.files || input.files.length === 0) {
  22459. this.remove();
  22460. } else {
  22461. this._uiManager.enableWaiting(true);
  22462. const data = await this._uiManager.imageManager.getFromFile(input.files[0]);
  22463. this._reportTelemetry({
  22464. action: "pdfjs.image.image_selected",
  22465. data: {
  22466. alt_text_modal: this._uiManager.useNewAltTextFlow
  22467. }
  22468. });
  22469. this.#getBitmapFetched(data);
  22470. }
  22471. resolve();
  22472. }, {
  22473. signal
  22474. });
  22475. input.addEventListener("cancel", () => {
  22476. this.remove();
  22477. resolve();
  22478. }, {
  22479. signal
  22480. });
  22481. }).finally(() => this.#getBitmapDone());
  22482. input.click();
  22483. }
  22484. remove() {
  22485. if (this.#bitmapId) {
  22486. this.#bitmap = null;
  22487. this._uiManager.imageManager.deleteId(this.#bitmapId);
  22488. this.#canvas?.remove();
  22489. this.#canvas = null;
  22490. this.#observer?.disconnect();
  22491. this.#observer = null;
  22492. if (this.#resizeTimeoutId) {
  22493. clearTimeout(this.#resizeTimeoutId);
  22494. this.#resizeTimeoutId = null;
  22495. }
  22496. }
  22497. super.remove();
  22498. }
  22499. rebuild() {
  22500. if (!this.parent) {
  22501. if (this.#bitmapId) {
  22502. this.#getBitmap();
  22503. }
  22504. return;
  22505. }
  22506. super.rebuild();
  22507. if (this.div === null) {
  22508. return;
  22509. }
  22510. if (this.#bitmapId && this.#canvas === null) {
  22511. this.#getBitmap();
  22512. }
  22513. if (!this.isAttachedToDOM) {
  22514. this.parent.add(this);
  22515. }
  22516. }
  22517. onceAdded() {
  22518. this._isDraggable = true;
  22519. this.div.focus();
  22520. }
  22521. isEmpty() {
  22522. return !(this.#bitmapPromise || this.#bitmap || this.#bitmapUrl || this.#bitmapFile || this.#bitmapId);
  22523. }
  22524. get isResizable() {
  22525. return true;
  22526. }
  22527. render() {
  22528. if (this.div) {
  22529. return this.div;
  22530. }
  22531. let baseX, baseY;
  22532. if (this.width) {
  22533. baseX = this.x;
  22534. baseY = this.y;
  22535. }
  22536. super.render();
  22537. this.div.hidden = true;
  22538. this.div.setAttribute("role", "figure");
  22539. this.addAltTextButton();
  22540. if (this.#bitmap) {
  22541. this.#createCanvas();
  22542. } else {
  22543. this.#getBitmap();
  22544. }
  22545. if (this.width && !this.annotationElementId) {
  22546. const [parentWidth, parentHeight] = this.parentDimensions;
  22547. this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
  22548. }
  22549. return this.div;
  22550. }
  22551. #createCanvas() {
  22552. const {
  22553. div
  22554. } = this;
  22555. let {
  22556. width,
  22557. height
  22558. } = this.#bitmap;
  22559. const [pageWidth, pageHeight] = this.pageDimensions;
  22560. const MAX_RATIO = 0.75;
  22561. if (this.width) {
  22562. width = this.width * pageWidth;
  22563. height = this.height * pageHeight;
  22564. } else if (width > MAX_RATIO * pageWidth || height > MAX_RATIO * pageHeight) {
  22565. const factor = Math.min(MAX_RATIO * pageWidth / width, MAX_RATIO * pageHeight / height);
  22566. width *= factor;
  22567. height *= factor;
  22568. }
  22569. const [parentWidth, parentHeight] = this.parentDimensions;
  22570. this.setDims(width * parentWidth / pageWidth, height * parentHeight / pageHeight);
  22571. this._uiManager.enableWaiting(false);
  22572. const canvas = this.#canvas = document.createElement("canvas");
  22573. canvas.setAttribute("role", "img");
  22574. this.addContainer(canvas);
  22575. if (!this._uiManager.useNewAltTextWhenAddingImage || !this._uiManager.useNewAltTextFlow || this.annotationElementId) {
  22576. div.hidden = false;
  22577. }
  22578. this.#drawBitmap(width, height);
  22579. this.#createObserver();
  22580. if (!this.#hasBeenAddedInUndoStack) {
  22581. this.parent.addUndoableEditor(this);
  22582. this.#hasBeenAddedInUndoStack = true;
  22583. }
  22584. this._reportTelemetry({
  22585. action: "inserted_image"
  22586. });
  22587. if (this.#bitmapFileName) {
  22588. canvas.setAttribute("aria-label", this.#bitmapFileName);
  22589. }
  22590. }
  22591. copyCanvas(maxDataDimension, maxPreviewDimension, createImageData = false) {
  22592. if (!maxDataDimension) {
  22593. maxDataDimension = 224;
  22594. }
  22595. const {
  22596. width: bitmapWidth,
  22597. height: bitmapHeight
  22598. } = this.#bitmap;
  22599. const outputScale = new OutputScale();
  22600. let bitmap = this.#bitmap;
  22601. let width = bitmapWidth,
  22602. height = bitmapHeight;
  22603. let canvas = null;
  22604. if (maxPreviewDimension) {
  22605. if (bitmapWidth > maxPreviewDimension || bitmapHeight > maxPreviewDimension) {
  22606. const ratio = Math.min(maxPreviewDimension / bitmapWidth, maxPreviewDimension / bitmapHeight);
  22607. width = Math.floor(bitmapWidth * ratio);
  22608. height = Math.floor(bitmapHeight * ratio);
  22609. }
  22610. canvas = document.createElement("canvas");
  22611. const scaledWidth = canvas.width = Math.ceil(width * outputScale.sx);
  22612. const scaledHeight = canvas.height = Math.ceil(height * outputScale.sy);
  22613. if (!this.#isSvg) {
  22614. bitmap = this.#scaleBitmap(scaledWidth, scaledHeight);
  22615. }
  22616. const ctx = canvas.getContext("2d");
  22617. ctx.filter = this._uiManager.hcmFilter;
  22618. let white = "white",
  22619. black = "#cfcfd8";
  22620. if (this._uiManager.hcmFilter !== "none") {
  22621. black = "black";
  22622. } else if (window.matchMedia?.("(prefers-color-scheme: dark)").matches) {
  22623. white = "#8f8f9d";
  22624. black = "#42414d";
  22625. }
  22626. const boxDim = 15;
  22627. const boxDimWidth = boxDim * outputScale.sx;
  22628. const boxDimHeight = boxDim * outputScale.sy;
  22629. const pattern = new OffscreenCanvas(boxDimWidth * 2, boxDimHeight * 2);
  22630. const patternCtx = pattern.getContext("2d");
  22631. patternCtx.fillStyle = white;
  22632. patternCtx.fillRect(0, 0, boxDimWidth * 2, boxDimHeight * 2);
  22633. patternCtx.fillStyle = black;
  22634. patternCtx.fillRect(0, 0, boxDimWidth, boxDimHeight);
  22635. patternCtx.fillRect(boxDimWidth, boxDimHeight, boxDimWidth, boxDimHeight);
  22636. ctx.fillStyle = ctx.createPattern(pattern, "repeat");
  22637. ctx.fillRect(0, 0, scaledWidth, scaledHeight);
  22638. ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight);
  22639. }
  22640. let imageData = null;
  22641. if (createImageData) {
  22642. let dataWidth, dataHeight;
  22643. if (outputScale.symmetric && bitmap.width < maxDataDimension && bitmap.height < maxDataDimension) {
  22644. dataWidth = bitmap.width;
  22645. dataHeight = bitmap.height;
  22646. } else {
  22647. bitmap = this.#bitmap;
  22648. if (bitmapWidth > maxDataDimension || bitmapHeight > maxDataDimension) {
  22649. const ratio = Math.min(maxDataDimension / bitmapWidth, maxDataDimension / bitmapHeight);
  22650. dataWidth = Math.floor(bitmapWidth * ratio);
  22651. dataHeight = Math.floor(bitmapHeight * ratio);
  22652. if (!this.#isSvg) {
  22653. bitmap = this.#scaleBitmap(dataWidth, dataHeight);
  22654. }
  22655. }
  22656. }
  22657. const offscreen = new OffscreenCanvas(dataWidth, dataHeight);
  22658. const offscreenCtx = offscreen.getContext("2d", {
  22659. willReadFrequently: true
  22660. });
  22661. offscreenCtx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, dataWidth, dataHeight);
  22662. imageData = {
  22663. width: dataWidth,
  22664. height: dataHeight,
  22665. data: offscreenCtx.getImageData(0, 0, dataWidth, dataHeight).data
  22666. };
  22667. }
  22668. return {
  22669. canvas,
  22670. width,
  22671. height,
  22672. imageData
  22673. };
  22674. }
  22675. #setDimensions(width, height) {
  22676. const [parentWidth, parentHeight] = this.parentDimensions;
  22677. this.width = width / parentWidth;
  22678. this.height = height / parentHeight;
  22679. if (this._initialOptions?.isCentered) {
  22680. this.center();
  22681. } else {
  22682. this.fixAndSetPosition();
  22683. }
  22684. this._initialOptions = null;
  22685. if (this.#resizeTimeoutId !== null) {
  22686. clearTimeout(this.#resizeTimeoutId);
  22687. }
  22688. const TIME_TO_WAIT = 200;
  22689. this.#resizeTimeoutId = setTimeout(() => {
  22690. this.#resizeTimeoutId = null;
  22691. this.#drawBitmap(width, height);
  22692. }, TIME_TO_WAIT);
  22693. }
  22694. #scaleBitmap(width, height) {
  22695. const {
  22696. width: bitmapWidth,
  22697. height: bitmapHeight
  22698. } = this.#bitmap;
  22699. let newWidth = bitmapWidth;
  22700. let newHeight = bitmapHeight;
  22701. let bitmap = this.#bitmap;
  22702. while (newWidth > 2 * width || newHeight > 2 * height) {
  22703. const prevWidth = newWidth;
  22704. const prevHeight = newHeight;
  22705. if (newWidth > 2 * width) {
  22706. newWidth = newWidth >= 16384 ? Math.floor(newWidth / 2) - 1 : Math.ceil(newWidth / 2);
  22707. }
  22708. if (newHeight > 2 * height) {
  22709. newHeight = newHeight >= 16384 ? Math.floor(newHeight / 2) - 1 : Math.ceil(newHeight / 2);
  22710. }
  22711. const offscreen = new OffscreenCanvas(newWidth, newHeight);
  22712. const ctx = offscreen.getContext("2d");
  22713. ctx.drawImage(bitmap, 0, 0, prevWidth, prevHeight, 0, 0, newWidth, newHeight);
  22714. bitmap = offscreen.transferToImageBitmap();
  22715. }
  22716. return bitmap;
  22717. }
  22718. #drawBitmap(width, height) {
  22719. const outputScale = new OutputScale();
  22720. const scaledWidth = Math.ceil(width * outputScale.sx);
  22721. const scaledHeight = Math.ceil(height * outputScale.sy);
  22722. const canvas = this.#canvas;
  22723. if (!canvas || canvas.width === scaledWidth && canvas.height === scaledHeight) {
  22724. return;
  22725. }
  22726. canvas.width = scaledWidth;
  22727. canvas.height = scaledHeight;
  22728. const bitmap = this.#isSvg ? this.#bitmap : this.#scaleBitmap(scaledWidth, scaledHeight);
  22729. const ctx = canvas.getContext("2d");
  22730. ctx.filter = this._uiManager.hcmFilter;
  22731. ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight);
  22732. }
  22733. getImageForAltText() {
  22734. return this.#canvas;
  22735. }
  22736. #serializeBitmap(toUrl) {
  22737. if (toUrl) {
  22738. if (this.#isSvg) {
  22739. const url = this._uiManager.imageManager.getSvgUrl(this.#bitmapId);
  22740. if (url) {
  22741. return url;
  22742. }
  22743. }
  22744. const canvas = document.createElement("canvas");
  22745. ({
  22746. width: canvas.width,
  22747. height: canvas.height
  22748. } = this.#bitmap);
  22749. const ctx = canvas.getContext("2d");
  22750. ctx.drawImage(this.#bitmap, 0, 0);
  22751. return canvas.toDataURL();
  22752. }
  22753. if (this.#isSvg) {
  22754. const [pageWidth, pageHeight] = this.pageDimensions;
  22755. const width = Math.round(this.width * pageWidth * PixelsPerInch.PDF_TO_CSS_UNITS);
  22756. const height = Math.round(this.height * pageHeight * PixelsPerInch.PDF_TO_CSS_UNITS);
  22757. const offscreen = new OffscreenCanvas(width, height);
  22758. const ctx = offscreen.getContext("2d");
  22759. ctx.drawImage(this.#bitmap, 0, 0, this.#bitmap.width, this.#bitmap.height, 0, 0, width, height);
  22760. return offscreen.transferToImageBitmap();
  22761. }
  22762. return structuredClone(this.#bitmap);
  22763. }
  22764. #createObserver() {
  22765. if (!this._uiManager._signal) {
  22766. return;
  22767. }
  22768. this.#observer = new ResizeObserver(entries => {
  22769. const rect = entries[0].contentRect;
  22770. if (rect.width && rect.height) {
  22771. this.#setDimensions(rect.width, rect.height);
  22772. }
  22773. });
  22774. this.#observer.observe(this.div);
  22775. this._uiManager._signal.addEventListener("abort", () => {
  22776. this.#observer?.disconnect();
  22777. this.#observer = null;
  22778. }, {
  22779. once: true
  22780. });
  22781. }
  22782. static async deserialize(data, parent, uiManager) {
  22783. let initialData = null;
  22784. if (data instanceof StampAnnotationElement) {
  22785. const {
  22786. data: {
  22787. rect,
  22788. rotation,
  22789. id,
  22790. structParent,
  22791. popupRef
  22792. },
  22793. container,
  22794. parent: {
  22795. page: {
  22796. pageNumber
  22797. }
  22798. }
  22799. } = data;
  22800. const canvas = container.querySelector("canvas");
  22801. const imageData = uiManager.imageManager.getFromCanvas(container.id, canvas);
  22802. canvas.remove();
  22803. const altText = (await parent._structTree.getAriaAttributes(`${AnnotationPrefix}${id}`))?.get("aria-label") || "";
  22804. initialData = data = {
  22805. annotationType: AnnotationEditorType.STAMP,
  22806. bitmapId: imageData.id,
  22807. bitmap: imageData.bitmap,
  22808. pageIndex: pageNumber - 1,
  22809. rect: rect.slice(0),
  22810. rotation,
  22811. id,
  22812. deleted: false,
  22813. accessibilityData: {
  22814. decorative: false,
  22815. altText
  22816. },
  22817. isSvg: false,
  22818. structParent,
  22819. popupRef
  22820. };
  22821. }
  22822. const editor = await super.deserialize(data, parent, uiManager);
  22823. const {
  22824. rect,
  22825. bitmap,
  22826. bitmapUrl,
  22827. bitmapId,
  22828. isSvg,
  22829. accessibilityData
  22830. } = data;
  22831. if (bitmapId && uiManager.imageManager.isValidId(bitmapId)) {
  22832. editor.#bitmapId = bitmapId;
  22833. if (bitmap) {
  22834. editor.#bitmap = bitmap;
  22835. }
  22836. } else {
  22837. editor.#bitmapUrl = bitmapUrl;
  22838. }
  22839. editor.#isSvg = isSvg;
  22840. const [parentWidth, parentHeight] = editor.pageDimensions;
  22841. editor.width = (rect[2] - rect[0]) / parentWidth;
  22842. editor.height = (rect[3] - rect[1]) / parentHeight;
  22843. editor.annotationElementId = data.id || null;
  22844. if (accessibilityData) {
  22845. editor.altTextData = accessibilityData;
  22846. }
  22847. editor._initialData = initialData;
  22848. editor.#hasBeenAddedInUndoStack = !!initialData;
  22849. return editor;
  22850. }
  22851. serialize(isForCopying = false, context = null) {
  22852. if (this.isEmpty()) {
  22853. return null;
  22854. }
  22855. if (this.deleted) {
  22856. return this.serializeDeleted();
  22857. }
  22858. const serialized = {
  22859. annotationType: AnnotationEditorType.STAMP,
  22860. bitmapId: this.#bitmapId,
  22861. pageIndex: this.pageIndex,
  22862. rect: this.getRect(0, 0),
  22863. rotation: this.rotation,
  22864. isSvg: this.#isSvg,
  22865. structTreeParentId: this._structTreeParentId
  22866. };
  22867. if (isForCopying) {
  22868. serialized.bitmapUrl = this.#serializeBitmap(true);
  22869. serialized.accessibilityData = this.serializeAltText(true);
  22870. return serialized;
  22871. }
  22872. const {
  22873. decorative,
  22874. altText
  22875. } = this.serializeAltText(false);
  22876. if (!decorative && altText) {
  22877. serialized.accessibilityData = {
  22878. type: "Figure",
  22879. alt: altText
  22880. };
  22881. }
  22882. if (this.annotationElementId) {
  22883. const changes = this.#hasElementChanged(serialized);
  22884. if (changes.isSame) {
  22885. return null;
  22886. }
  22887. if (changes.isSameAltText) {
  22888. delete serialized.accessibilityData;
  22889. } else {
  22890. serialized.accessibilityData.structParent = this._initialData.structParent ?? -1;
  22891. }
  22892. }
  22893. serialized.id = this.annotationElementId;
  22894. if (context === null) {
  22895. return serialized;
  22896. }
  22897. context.stamps ||= new Map();
  22898. const area = this.#isSvg ? (serialized.rect[2] - serialized.rect[0]) * (serialized.rect[3] - serialized.rect[1]) : null;
  22899. if (!context.stamps.has(this.#bitmapId)) {
  22900. context.stamps.set(this.#bitmapId, {
  22901. area,
  22902. serialized
  22903. });
  22904. serialized.bitmap = this.#serializeBitmap(false);
  22905. } else if (this.#isSvg) {
  22906. const prevData = context.stamps.get(this.#bitmapId);
  22907. if (area > prevData.area) {
  22908. prevData.area = area;
  22909. prevData.serialized.bitmap.close();
  22910. prevData.serialized.bitmap = this.#serializeBitmap(false);
  22911. }
  22912. }
  22913. return serialized;
  22914. }
  22915. #hasElementChanged(serialized) {
  22916. const {
  22917. rect,
  22918. pageIndex,
  22919. accessibilityData: {
  22920. altText
  22921. }
  22922. } = this._initialData;
  22923. const isSameRect = serialized.rect.every((x, i) => Math.abs(x - rect[i]) < 1);
  22924. const isSamePageIndex = serialized.pageIndex === pageIndex;
  22925. const isSameAltText = (serialized.accessibilityData?.alt || "") === altText;
  22926. return {
  22927. isSame: isSameRect && isSamePageIndex && isSameAltText,
  22928. isSameAltText
  22929. };
  22930. }
  22931. renderAnnotationElement(annotation) {
  22932. annotation.updateEdited({
  22933. rect: this.getRect(0, 0)
  22934. });
  22935. return null;
  22936. }
  22937. }
  22938. ;// ./src/display/editor/annotation_editor_layer.js
  22939. class AnnotationEditorLayer {
  22940. #accessibilityManager;
  22941. #allowClick = false;
  22942. #annotationLayer = null;
  22943. #clickAC = null;
  22944. #editorFocusTimeoutId = null;
  22945. #editors = new Map();
  22946. #hadPointerDown = false;
  22947. #isCleaningUp = false;
  22948. #isDisabling = false;
  22949. #textLayer = null;
  22950. #textSelectionAC = null;
  22951. #uiManager;
  22952. static _initialized = false;
  22953. static #editorTypes = new Map([FreeTextEditor, InkEditor, StampEditor, HighlightEditor].map(type => [type._editorType, type]));
  22954. constructor({
  22955. uiManager,
  22956. pageIndex,
  22957. div,
  22958. structTreeLayer,
  22959. accessibilityManager,
  22960. annotationLayer,
  22961. drawLayer,
  22962. textLayer,
  22963. viewport,
  22964. l10n
  22965. }) {
  22966. const editorTypes = [...AnnotationEditorLayer.#editorTypes.values()];
  22967. if (!AnnotationEditorLayer._initialized) {
  22968. AnnotationEditorLayer._initialized = true;
  22969. for (const editorType of editorTypes) {
  22970. editorType.initialize(l10n, uiManager);
  22971. }
  22972. }
  22973. uiManager.registerEditorTypes(editorTypes);
  22974. this.#uiManager = uiManager;
  22975. this.pageIndex = pageIndex;
  22976. this.div = div;
  22977. this.#accessibilityManager = accessibilityManager;
  22978. this.#annotationLayer = annotationLayer;
  22979. this.viewport = viewport;
  22980. this.#textLayer = textLayer;
  22981. this.drawLayer = drawLayer;
  22982. this._structTree = structTreeLayer;
  22983. this.#uiManager.addLayer(this);
  22984. }
  22985. get isEmpty() {
  22986. return this.#editors.size === 0;
  22987. }
  22988. get isInvisible() {
  22989. return this.isEmpty && this.#uiManager.getMode() === AnnotationEditorType.NONE;
  22990. }
  22991. updateToolbar(mode) {
  22992. this.#uiManager.updateToolbar(mode);
  22993. }
  22994. updateMode(mode = this.#uiManager.getMode()) {
  22995. this.#cleanup();
  22996. switch (mode) {
  22997. case AnnotationEditorType.NONE:
  22998. this.disableTextSelection();
  22999. this.togglePointerEvents(false);
  23000. this.toggleAnnotationLayerPointerEvents(true);
  23001. this.disableClick();
  23002. return;
  23003. case AnnotationEditorType.INK:
  23004. this.addInkEditorIfNeeded(false);
  23005. this.disableTextSelection();
  23006. this.togglePointerEvents(true);
  23007. this.disableClick();
  23008. break;
  23009. case AnnotationEditorType.HIGHLIGHT:
  23010. this.enableTextSelection();
  23011. this.togglePointerEvents(false);
  23012. this.disableClick();
  23013. break;
  23014. default:
  23015. this.disableTextSelection();
  23016. this.togglePointerEvents(true);
  23017. this.enableClick();
  23018. }
  23019. this.toggleAnnotationLayerPointerEvents(false);
  23020. const {
  23021. classList
  23022. } = this.div;
  23023. for (const editorType of AnnotationEditorLayer.#editorTypes.values()) {
  23024. classList.toggle(`${editorType._type}Editing`, mode === editorType._editorType);
  23025. }
  23026. this.div.hidden = false;
  23027. }
  23028. hasTextLayer(textLayer) {
  23029. return textLayer === this.#textLayer?.div;
  23030. }
  23031. addInkEditorIfNeeded(isCommitting) {
  23032. if (this.#uiManager.getMode() !== AnnotationEditorType.INK) {
  23033. return;
  23034. }
  23035. if (!isCommitting) {
  23036. for (const editor of this.#editors.values()) {
  23037. if (editor.isEmpty()) {
  23038. editor.setInBackground();
  23039. return;
  23040. }
  23041. }
  23042. }
  23043. const editor = this.createAndAddNewEditor({
  23044. offsetX: 0,
  23045. offsetY: 0
  23046. }, false);
  23047. editor.setInBackground();
  23048. }
  23049. setEditingState(isEditing) {
  23050. this.#uiManager.setEditingState(isEditing);
  23051. }
  23052. addCommands(params) {
  23053. this.#uiManager.addCommands(params);
  23054. }
  23055. toggleDrawing(enabled = false) {
  23056. this.div.classList.toggle("drawing", !enabled);
  23057. }
  23058. togglePointerEvents(enabled = false) {
  23059. this.div.classList.toggle("disabled", !enabled);
  23060. }
  23061. toggleAnnotationLayerPointerEvents(enabled = false) {
  23062. this.#annotationLayer?.div.classList.toggle("disabled", !enabled);
  23063. }
  23064. async enable() {
  23065. this.div.tabIndex = 0;
  23066. this.togglePointerEvents(true);
  23067. const annotationElementIds = new Set();
  23068. for (const editor of this.#editors.values()) {
  23069. editor.enableEditing();
  23070. editor.show(true);
  23071. if (editor.annotationElementId) {
  23072. this.#uiManager.removeChangedExistingAnnotation(editor);
  23073. annotationElementIds.add(editor.annotationElementId);
  23074. }
  23075. }
  23076. if (!this.#annotationLayer) {
  23077. return;
  23078. }
  23079. const editables = this.#annotationLayer.getEditableAnnotations();
  23080. for (const editable of editables) {
  23081. editable.hide();
  23082. if (this.#uiManager.isDeletedAnnotationElement(editable.data.id)) {
  23083. continue;
  23084. }
  23085. if (annotationElementIds.has(editable.data.id)) {
  23086. continue;
  23087. }
  23088. const editor = await this.deserialize(editable);
  23089. if (!editor) {
  23090. continue;
  23091. }
  23092. this.addOrRebuild(editor);
  23093. editor.enableEditing();
  23094. }
  23095. }
  23096. disable() {
  23097. this.#isDisabling = true;
  23098. this.div.tabIndex = -1;
  23099. this.togglePointerEvents(false);
  23100. const changedAnnotations = new Map();
  23101. const resetAnnotations = new Map();
  23102. for (const editor of this.#editors.values()) {
  23103. editor.disableEditing();
  23104. if (!editor.annotationElementId) {
  23105. continue;
  23106. }
  23107. if (editor.serialize() !== null) {
  23108. changedAnnotations.set(editor.annotationElementId, editor);
  23109. continue;
  23110. } else {
  23111. resetAnnotations.set(editor.annotationElementId, editor);
  23112. }
  23113. this.getEditableAnnotation(editor.annotationElementId)?.show();
  23114. editor.remove();
  23115. }
  23116. if (this.#annotationLayer) {
  23117. const editables = this.#annotationLayer.getEditableAnnotations();
  23118. for (const editable of editables) {
  23119. const {
  23120. id
  23121. } = editable.data;
  23122. if (this.#uiManager.isDeletedAnnotationElement(id)) {
  23123. continue;
  23124. }
  23125. let editor = resetAnnotations.get(id);
  23126. if (editor) {
  23127. editor.resetAnnotationElement(editable);
  23128. editor.show(false);
  23129. editable.show();
  23130. continue;
  23131. }
  23132. editor = changedAnnotations.get(id);
  23133. if (editor) {
  23134. this.#uiManager.addChangedExistingAnnotation(editor);
  23135. if (editor.renderAnnotationElement(editable)) {
  23136. editor.show(false);
  23137. }
  23138. }
  23139. editable.show();
  23140. }
  23141. }
  23142. this.#cleanup();
  23143. if (this.isEmpty) {
  23144. this.div.hidden = true;
  23145. }
  23146. const {
  23147. classList
  23148. } = this.div;
  23149. for (const editorType of AnnotationEditorLayer.#editorTypes.values()) {
  23150. classList.remove(`${editorType._type}Editing`);
  23151. }
  23152. this.disableTextSelection();
  23153. this.toggleAnnotationLayerPointerEvents(true);
  23154. this.#isDisabling = false;
  23155. }
  23156. getEditableAnnotation(id) {
  23157. return this.#annotationLayer?.getEditableAnnotation(id) || null;
  23158. }
  23159. setActiveEditor(editor) {
  23160. const currentActive = this.#uiManager.getActive();
  23161. if (currentActive === editor) {
  23162. return;
  23163. }
  23164. this.#uiManager.setActiveEditor(editor);
  23165. }
  23166. enableTextSelection() {
  23167. this.div.tabIndex = -1;
  23168. if (this.#textLayer?.div && !this.#textSelectionAC) {
  23169. this.#textSelectionAC = new AbortController();
  23170. const signal = this.#uiManager.combinedSignal(this.#textSelectionAC);
  23171. this.#textLayer.div.addEventListener("pointerdown", this.#textLayerPointerDown.bind(this), {
  23172. signal
  23173. });
  23174. this.#textLayer.div.classList.add("highlighting");
  23175. }
  23176. }
  23177. disableTextSelection() {
  23178. this.div.tabIndex = 0;
  23179. if (this.#textLayer?.div && this.#textSelectionAC) {
  23180. this.#textSelectionAC.abort();
  23181. this.#textSelectionAC = null;
  23182. this.#textLayer.div.classList.remove("highlighting");
  23183. }
  23184. }
  23185. #textLayerPointerDown(event) {
  23186. this.#uiManager.unselectAll();
  23187. const {
  23188. target
  23189. } = event;
  23190. if (target === this.#textLayer.div || (target.getAttribute("role") === "img" || target.classList.contains("endOfContent")) && this.#textLayer.div.contains(target)) {
  23191. const {
  23192. isMac
  23193. } = util_FeatureTest.platform;
  23194. if (event.button !== 0 || event.ctrlKey && isMac) {
  23195. return;
  23196. }
  23197. this.#uiManager.showAllEditors("highlight", true, true);
  23198. this.#textLayer.div.classList.add("free");
  23199. this.toggleDrawing();
  23200. HighlightEditor.startHighlighting(this, this.#uiManager.direction === "ltr", {
  23201. target: this.#textLayer.div,
  23202. x: event.x,
  23203. y: event.y
  23204. });
  23205. this.#textLayer.div.addEventListener("pointerup", () => {
  23206. this.#textLayer.div.classList.remove("free");
  23207. this.toggleDrawing(true);
  23208. }, {
  23209. once: true,
  23210. signal: this.#uiManager._signal
  23211. });
  23212. event.preventDefault();
  23213. }
  23214. }
  23215. enableClick() {
  23216. if (this.#clickAC) {
  23217. return;
  23218. }
  23219. this.#clickAC = new AbortController();
  23220. const signal = this.#uiManager.combinedSignal(this.#clickAC);
  23221. this.div.addEventListener("pointerdown", this.pointerdown.bind(this), {
  23222. signal
  23223. });
  23224. this.div.addEventListener("pointerup", this.pointerup.bind(this), {
  23225. signal
  23226. });
  23227. }
  23228. disableClick() {
  23229. this.#clickAC?.abort();
  23230. this.#clickAC = null;
  23231. }
  23232. attach(editor) {
  23233. this.#editors.set(editor.id, editor);
  23234. const {
  23235. annotationElementId
  23236. } = editor;
  23237. if (annotationElementId && this.#uiManager.isDeletedAnnotationElement(annotationElementId)) {
  23238. this.#uiManager.removeDeletedAnnotationElement(editor);
  23239. }
  23240. }
  23241. detach(editor) {
  23242. this.#editors.delete(editor.id);
  23243. this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
  23244. if (!this.#isDisabling && editor.annotationElementId) {
  23245. this.#uiManager.addDeletedAnnotationElement(editor);
  23246. }
  23247. }
  23248. remove(editor) {
  23249. this.detach(editor);
  23250. this.#uiManager.removeEditor(editor);
  23251. editor.div.remove();
  23252. editor.isAttachedToDOM = false;
  23253. if (!this.#isCleaningUp) {
  23254. this.addInkEditorIfNeeded(false);
  23255. }
  23256. }
  23257. changeParent(editor) {
  23258. if (editor.parent === this) {
  23259. return;
  23260. }
  23261. if (editor.parent && editor.annotationElementId) {
  23262. this.#uiManager.addDeletedAnnotationElement(editor.annotationElementId);
  23263. AnnotationEditor.deleteAnnotationElement(editor);
  23264. editor.annotationElementId = null;
  23265. }
  23266. this.attach(editor);
  23267. editor.parent?.detach(editor);
  23268. editor.setParent(this);
  23269. if (editor.div && editor.isAttachedToDOM) {
  23270. editor.div.remove();
  23271. this.div.append(editor.div);
  23272. }
  23273. }
  23274. add(editor) {
  23275. if (editor.parent === this && editor.isAttachedToDOM) {
  23276. return;
  23277. }
  23278. this.changeParent(editor);
  23279. this.#uiManager.addEditor(editor);
  23280. this.attach(editor);
  23281. if (!editor.isAttachedToDOM) {
  23282. const div = editor.render();
  23283. this.div.append(div);
  23284. editor.isAttachedToDOM = true;
  23285. }
  23286. editor.fixAndSetPosition();
  23287. editor.onceAdded();
  23288. this.#uiManager.addToAnnotationStorage(editor);
  23289. editor._reportTelemetry(editor.telemetryInitialData);
  23290. }
  23291. moveEditorInDOM(editor) {
  23292. if (!editor.isAttachedToDOM) {
  23293. return;
  23294. }
  23295. const {
  23296. activeElement
  23297. } = document;
  23298. if (editor.div.contains(activeElement) && !this.#editorFocusTimeoutId) {
  23299. editor._focusEventsAllowed = false;
  23300. this.#editorFocusTimeoutId = setTimeout(() => {
  23301. this.#editorFocusTimeoutId = null;
  23302. if (!editor.div.contains(document.activeElement)) {
  23303. editor.div.addEventListener("focusin", () => {
  23304. editor._focusEventsAllowed = true;
  23305. }, {
  23306. once: true,
  23307. signal: this.#uiManager._signal
  23308. });
  23309. activeElement.focus();
  23310. } else {
  23311. editor._focusEventsAllowed = true;
  23312. }
  23313. }, 0);
  23314. }
  23315. editor._structTreeParentId = this.#accessibilityManager?.moveElementInDOM(this.div, editor.div, editor.contentDiv, true);
  23316. }
  23317. addOrRebuild(editor) {
  23318. if (editor.needsToBeRebuilt()) {
  23319. editor.parent ||= this;
  23320. editor.rebuild();
  23321. editor.show();
  23322. } else {
  23323. this.add(editor);
  23324. }
  23325. }
  23326. addUndoableEditor(editor) {
  23327. const cmd = () => editor._uiManager.rebuild(editor);
  23328. const undo = () => {
  23329. editor.remove();
  23330. };
  23331. this.addCommands({
  23332. cmd,
  23333. undo,
  23334. mustExec: false
  23335. });
  23336. }
  23337. getNextId() {
  23338. return this.#uiManager.getId();
  23339. }
  23340. get #currentEditorType() {
  23341. return AnnotationEditorLayer.#editorTypes.get(this.#uiManager.getMode());
  23342. }
  23343. combinedSignal(ac) {
  23344. return this.#uiManager.combinedSignal(ac);
  23345. }
  23346. #createNewEditor(params) {
  23347. const editorType = this.#currentEditorType;
  23348. return editorType ? new editorType.prototype.constructor(params) : null;
  23349. }
  23350. canCreateNewEmptyEditor() {
  23351. return this.#currentEditorType?.canCreateNewEmptyEditor();
  23352. }
  23353. pasteEditor(mode, params) {
  23354. this.#uiManager.updateToolbar(mode);
  23355. this.#uiManager.updateMode(mode);
  23356. const {
  23357. offsetX,
  23358. offsetY
  23359. } = this.#getCenterPoint();
  23360. const id = this.getNextId();
  23361. const editor = this.#createNewEditor({
  23362. parent: this,
  23363. id,
  23364. x: offsetX,
  23365. y: offsetY,
  23366. uiManager: this.#uiManager,
  23367. isCentered: true,
  23368. ...params
  23369. });
  23370. if (editor) {
  23371. this.add(editor);
  23372. }
  23373. }
  23374. async deserialize(data) {
  23375. return (await AnnotationEditorLayer.#editorTypes.get(data.annotationType ?? data.annotationEditorType)?.deserialize(data, this, this.#uiManager)) || null;
  23376. }
  23377. createAndAddNewEditor(event, isCentered, data = {}) {
  23378. const id = this.getNextId();
  23379. const editor = this.#createNewEditor({
  23380. parent: this,
  23381. id,
  23382. x: event.offsetX,
  23383. y: event.offsetY,
  23384. uiManager: this.#uiManager,
  23385. isCentered,
  23386. ...data
  23387. });
  23388. if (editor) {
  23389. this.add(editor);
  23390. }
  23391. return editor;
  23392. }
  23393. #getCenterPoint() {
  23394. const {
  23395. x,
  23396. y,
  23397. width,
  23398. height
  23399. } = this.div.getBoundingClientRect();
  23400. const tlX = Math.max(0, x);
  23401. const tlY = Math.max(0, y);
  23402. const brX = Math.min(window.innerWidth, x + width);
  23403. const brY = Math.min(window.innerHeight, y + height);
  23404. const centerX = (tlX + brX) / 2 - x;
  23405. const centerY = (tlY + brY) / 2 - y;
  23406. const [offsetX, offsetY] = this.viewport.rotation % 180 === 0 ? [centerX, centerY] : [centerY, centerX];
  23407. return {
  23408. offsetX,
  23409. offsetY
  23410. };
  23411. }
  23412. addNewEditor() {
  23413. this.createAndAddNewEditor(this.#getCenterPoint(), true);
  23414. }
  23415. setSelected(editor) {
  23416. this.#uiManager.setSelected(editor);
  23417. }
  23418. toggleSelected(editor) {
  23419. this.#uiManager.toggleSelected(editor);
  23420. }
  23421. isSelected(editor) {
  23422. return this.#uiManager.isSelected(editor);
  23423. }
  23424. unselect(editor) {
  23425. this.#uiManager.unselect(editor);
  23426. }
  23427. pointerup(event) {
  23428. const {
  23429. isMac
  23430. } = util_FeatureTest.platform;
  23431. if (event.button !== 0 || event.ctrlKey && isMac) {
  23432. return;
  23433. }
  23434. if (event.target !== this.div) {
  23435. return;
  23436. }
  23437. if (!this.#hadPointerDown) {
  23438. return;
  23439. }
  23440. this.#hadPointerDown = false;
  23441. if (!this.#allowClick) {
  23442. this.#allowClick = true;
  23443. return;
  23444. }
  23445. if (this.#uiManager.getMode() === AnnotationEditorType.STAMP) {
  23446. this.#uiManager.unselectAll();
  23447. return;
  23448. }
  23449. this.createAndAddNewEditor(event, false);
  23450. }
  23451. pointerdown(event) {
  23452. if (this.#uiManager.getMode() === AnnotationEditorType.HIGHLIGHT) {
  23453. this.enableTextSelection();
  23454. }
  23455. if (this.#hadPointerDown) {
  23456. this.#hadPointerDown = false;
  23457. return;
  23458. }
  23459. const {
  23460. isMac
  23461. } = util_FeatureTest.platform;
  23462. if (event.button !== 0 || event.ctrlKey && isMac) {
  23463. return;
  23464. }
  23465. if (event.target !== this.div) {
  23466. return;
  23467. }
  23468. this.#hadPointerDown = true;
  23469. const editor = this.#uiManager.getActive();
  23470. this.#allowClick = !editor || editor.isEmpty();
  23471. }
  23472. findNewParent(editor, x, y) {
  23473. const layer = this.#uiManager.findParent(x, y);
  23474. if (layer === null || layer === this) {
  23475. return false;
  23476. }
  23477. layer.changeParent(editor);
  23478. return true;
  23479. }
  23480. destroy() {
  23481. if (this.#uiManager.getActive()?.parent === this) {
  23482. this.#uiManager.commitOrRemove();
  23483. this.#uiManager.setActiveEditor(null);
  23484. }
  23485. if (this.#editorFocusTimeoutId) {
  23486. clearTimeout(this.#editorFocusTimeoutId);
  23487. this.#editorFocusTimeoutId = null;
  23488. }
  23489. for (const editor of this.#editors.values()) {
  23490. this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
  23491. editor.setParent(null);
  23492. editor.isAttachedToDOM = false;
  23493. editor.div.remove();
  23494. }
  23495. this.div = null;
  23496. this.#editors.clear();
  23497. this.#uiManager.removeLayer(this);
  23498. }
  23499. #cleanup() {
  23500. this.#isCleaningUp = true;
  23501. for (const editor of this.#editors.values()) {
  23502. if (editor.isEmpty()) {
  23503. editor.remove();
  23504. }
  23505. }
  23506. this.#isCleaningUp = false;
  23507. }
  23508. render({
  23509. viewport
  23510. }) {
  23511. this.viewport = viewport;
  23512. setLayerDimensions(this.div, viewport);
  23513. for (const editor of this.#uiManager.getEditors(this.pageIndex)) {
  23514. this.add(editor);
  23515. editor.rebuild();
  23516. }
  23517. this.updateMode();
  23518. }
  23519. update({
  23520. viewport
  23521. }) {
  23522. this.#uiManager.commitOrRemove();
  23523. this.#cleanup();
  23524. const oldRotation = this.viewport.rotation;
  23525. const rotation = viewport.rotation;
  23526. this.viewport = viewport;
  23527. setLayerDimensions(this.div, {
  23528. rotation
  23529. });
  23530. if (oldRotation !== rotation) {
  23531. for (const editor of this.#editors.values()) {
  23532. editor.rotate(rotation);
  23533. }
  23534. }
  23535. this.addInkEditorIfNeeded(false);
  23536. }
  23537. get pageDimensions() {
  23538. const {
  23539. pageWidth,
  23540. pageHeight
  23541. } = this.viewport.rawDims;
  23542. return [pageWidth, pageHeight];
  23543. }
  23544. get scale() {
  23545. return this.#uiManager.viewParameters.realScale;
  23546. }
  23547. }
  23548. ;// ./src/display/draw_layer.js
  23549. class DrawLayer {
  23550. #parent = null;
  23551. #id = 0;
  23552. #mapping = new Map();
  23553. #toUpdate = new Map();
  23554. constructor({
  23555. pageIndex
  23556. }) {
  23557. this.pageIndex = pageIndex;
  23558. }
  23559. setParent(parent) {
  23560. if (!this.#parent) {
  23561. this.#parent = parent;
  23562. return;
  23563. }
  23564. if (this.#parent !== parent) {
  23565. if (this.#mapping.size > 0) {
  23566. for (const root of this.#mapping.values()) {
  23567. root.remove();
  23568. parent.append(root);
  23569. }
  23570. }
  23571. this.#parent = parent;
  23572. }
  23573. }
  23574. static get _svgFactory() {
  23575. return shadow(this, "_svgFactory", new DOMSVGFactory());
  23576. }
  23577. static #setBox(element, {
  23578. x = 0,
  23579. y = 0,
  23580. width = 1,
  23581. height = 1
  23582. } = {}) {
  23583. const {
  23584. style
  23585. } = element;
  23586. style.top = `${100 * y}%`;
  23587. style.left = `${100 * x}%`;
  23588. style.width = `${100 * width}%`;
  23589. style.height = `${100 * height}%`;
  23590. }
  23591. #createSVG(box) {
  23592. const svg = DrawLayer._svgFactory.create(1, 1, true);
  23593. this.#parent.append(svg);
  23594. svg.setAttribute("aria-hidden", true);
  23595. DrawLayer.#setBox(svg, box);
  23596. return svg;
  23597. }
  23598. #createClipPath(defs, pathId) {
  23599. const clipPath = DrawLayer._svgFactory.createElement("clipPath");
  23600. defs.append(clipPath);
  23601. const clipPathId = `clip_${pathId}`;
  23602. clipPath.setAttribute("id", clipPathId);
  23603. clipPath.setAttribute("clipPathUnits", "objectBoundingBox");
  23604. const clipPathUse = DrawLayer._svgFactory.createElement("use");
  23605. clipPath.append(clipPathUse);
  23606. clipPathUse.setAttribute("href", `#${pathId}`);
  23607. clipPathUse.classList.add("clip");
  23608. return clipPathId;
  23609. }
  23610. highlight(outlines, color, opacity, isPathUpdatable = false) {
  23611. const id = this.#id++;
  23612. const root = this.#createSVG(outlines.box);
  23613. root.classList.add("highlight");
  23614. if (outlines.free) {
  23615. root.classList.add("free");
  23616. }
  23617. const defs = DrawLayer._svgFactory.createElement("defs");
  23618. root.append(defs);
  23619. const path = DrawLayer._svgFactory.createElement("path");
  23620. defs.append(path);
  23621. const pathId = `path_p${this.pageIndex}_${id}`;
  23622. path.setAttribute("id", pathId);
  23623. path.setAttribute("d", outlines.toSVGPath());
  23624. if (isPathUpdatable) {
  23625. this.#toUpdate.set(id, path);
  23626. }
  23627. const clipPathId = this.#createClipPath(defs, pathId);
  23628. const use = DrawLayer._svgFactory.createElement("use");
  23629. root.append(use);
  23630. root.setAttribute("fill", color);
  23631. root.setAttribute("fill-opacity", opacity);
  23632. use.setAttribute("href", `#${pathId}`);
  23633. this.#mapping.set(id, root);
  23634. return {
  23635. id,
  23636. clipPathId: `url(#${clipPathId})`
  23637. };
  23638. }
  23639. highlightOutline(outlines) {
  23640. const id = this.#id++;
  23641. const root = this.#createSVG(outlines.box);
  23642. root.classList.add("highlightOutline");
  23643. const defs = DrawLayer._svgFactory.createElement("defs");
  23644. root.append(defs);
  23645. const path = DrawLayer._svgFactory.createElement("path");
  23646. defs.append(path);
  23647. const pathId = `path_p${this.pageIndex}_${id}`;
  23648. path.setAttribute("id", pathId);
  23649. path.setAttribute("d", outlines.toSVGPath());
  23650. path.setAttribute("vector-effect", "non-scaling-stroke");
  23651. let maskId;
  23652. if (outlines.free) {
  23653. root.classList.add("free");
  23654. const mask = DrawLayer._svgFactory.createElement("mask");
  23655. defs.append(mask);
  23656. maskId = `mask_p${this.pageIndex}_${id}`;
  23657. mask.setAttribute("id", maskId);
  23658. mask.setAttribute("maskUnits", "objectBoundingBox");
  23659. const rect = DrawLayer._svgFactory.createElement("rect");
  23660. mask.append(rect);
  23661. rect.setAttribute("width", "1");
  23662. rect.setAttribute("height", "1");
  23663. rect.setAttribute("fill", "white");
  23664. const use = DrawLayer._svgFactory.createElement("use");
  23665. mask.append(use);
  23666. use.setAttribute("href", `#${pathId}`);
  23667. use.setAttribute("stroke", "none");
  23668. use.setAttribute("fill", "black");
  23669. use.setAttribute("fill-rule", "nonzero");
  23670. use.classList.add("mask");
  23671. }
  23672. const use1 = DrawLayer._svgFactory.createElement("use");
  23673. root.append(use1);
  23674. use1.setAttribute("href", `#${pathId}`);
  23675. if (maskId) {
  23676. use1.setAttribute("mask", `url(#${maskId})`);
  23677. }
  23678. const use2 = use1.cloneNode();
  23679. root.append(use2);
  23680. use1.classList.add("mainOutline");
  23681. use2.classList.add("secondaryOutline");
  23682. this.#mapping.set(id, root);
  23683. return id;
  23684. }
  23685. finalizeLine(id, line) {
  23686. const path = this.#toUpdate.get(id);
  23687. this.#toUpdate.delete(id);
  23688. this.updateBox(id, line.box);
  23689. path.setAttribute("d", line.toSVGPath());
  23690. }
  23691. updateLine(id, line) {
  23692. const root = this.#mapping.get(id);
  23693. const defs = root.firstChild;
  23694. const path = defs.firstChild;
  23695. path.setAttribute("d", line.toSVGPath());
  23696. }
  23697. removeFreeHighlight(id) {
  23698. this.remove(id);
  23699. this.#toUpdate.delete(id);
  23700. }
  23701. updatePath(id, line) {
  23702. this.#toUpdate.get(id).setAttribute("d", line.toSVGPath());
  23703. }
  23704. updateBox(id, box) {
  23705. DrawLayer.#setBox(this.#mapping.get(id), box);
  23706. }
  23707. show(id, visible) {
  23708. this.#mapping.get(id).classList.toggle("hidden", !visible);
  23709. }
  23710. rotate(id, angle) {
  23711. this.#mapping.get(id).setAttribute("data-main-rotation", angle);
  23712. }
  23713. changeColor(id, color) {
  23714. this.#mapping.get(id).setAttribute("fill", color);
  23715. }
  23716. changeOpacity(id, opacity) {
  23717. this.#mapping.get(id).setAttribute("fill-opacity", opacity);
  23718. }
  23719. addClass(id, className) {
  23720. this.#mapping.get(id).classList.add(className);
  23721. }
  23722. removeClass(id, className) {
  23723. this.#mapping.get(id).classList.remove(className);
  23724. }
  23725. getSVGRoot(id) {
  23726. return this.#mapping.get(id);
  23727. }
  23728. remove(id) {
  23729. if (this.#parent === null) {
  23730. return;
  23731. }
  23732. this.#mapping.get(id).remove();
  23733. this.#mapping.delete(id);
  23734. }
  23735. destroy() {
  23736. this.#parent = null;
  23737. for (const root of this.#mapping.values()) {
  23738. root.remove();
  23739. }
  23740. this.#mapping.clear();
  23741. }
  23742. }
  23743. ;// ./src/pdf.js
  23744. const pdfjsVersion = "4.7.76";
  23745. const pdfjsBuild = "8b73b828b";
  23746. var __webpack_exports__AbortException = __webpack_exports__.AbortException;
  23747. var __webpack_exports__AnnotationEditorLayer = __webpack_exports__.AnnotationEditorLayer;
  23748. var __webpack_exports__AnnotationEditorParamsType = __webpack_exports__.AnnotationEditorParamsType;
  23749. var __webpack_exports__AnnotationEditorType = __webpack_exports__.AnnotationEditorType;
  23750. var __webpack_exports__AnnotationEditorUIManager = __webpack_exports__.AnnotationEditorUIManager;
  23751. var __webpack_exports__AnnotationLayer = __webpack_exports__.AnnotationLayer;
  23752. var __webpack_exports__AnnotationMode = __webpack_exports__.AnnotationMode;
  23753. var __webpack_exports__CMapCompressionType = __webpack_exports__.CMapCompressionType;
  23754. var __webpack_exports__ColorPicker = __webpack_exports__.ColorPicker;
  23755. var __webpack_exports__DOMSVGFactory = __webpack_exports__.DOMSVGFactory;
  23756. var __webpack_exports__DrawLayer = __webpack_exports__.DrawLayer;
  23757. var __webpack_exports__FeatureTest = __webpack_exports__.FeatureTest;
  23758. var __webpack_exports__GlobalWorkerOptions = __webpack_exports__.GlobalWorkerOptions;
  23759. var __webpack_exports__ImageKind = __webpack_exports__.ImageKind;
  23760. var __webpack_exports__InvalidPDFException = __webpack_exports__.InvalidPDFException;
  23761. var __webpack_exports__MissingPDFException = __webpack_exports__.MissingPDFException;
  23762. var __webpack_exports__OPS = __webpack_exports__.OPS;
  23763. var __webpack_exports__OutputScale = __webpack_exports__.OutputScale;
  23764. var __webpack_exports__PDFDataRangeTransport = __webpack_exports__.PDFDataRangeTransport;
  23765. var __webpack_exports__PDFDateString = __webpack_exports__.PDFDateString;
  23766. var __webpack_exports__PDFWorker = __webpack_exports__.PDFWorker;
  23767. var __webpack_exports__PasswordResponses = __webpack_exports__.PasswordResponses;
  23768. var __webpack_exports__PermissionFlag = __webpack_exports__.PermissionFlag;
  23769. var __webpack_exports__PixelsPerInch = __webpack_exports__.PixelsPerInch;
  23770. var __webpack_exports__RenderingCancelledException = __webpack_exports__.RenderingCancelledException;
  23771. var __webpack_exports__TextLayer = __webpack_exports__.TextLayer;
  23772. var __webpack_exports__UnexpectedResponseException = __webpack_exports__.UnexpectedResponseException;
  23773. var __webpack_exports__Util = __webpack_exports__.Util;
  23774. var __webpack_exports__VerbosityLevel = __webpack_exports__.VerbosityLevel;
  23775. var __webpack_exports__XfaLayer = __webpack_exports__.XfaLayer;
  23776. var __webpack_exports__build = __webpack_exports__.build;
  23777. var __webpack_exports__createValidAbsoluteUrl = __webpack_exports__.createValidAbsoluteUrl;
  23778. var __webpack_exports__fetchData = __webpack_exports__.fetchData;
  23779. var __webpack_exports__getDocument = __webpack_exports__.getDocument;
  23780. var __webpack_exports__getFilenameFromUrl = __webpack_exports__.getFilenameFromUrl;
  23781. var __webpack_exports__getPdfFilenameFromUrl = __webpack_exports__.getPdfFilenameFromUrl;
  23782. var __webpack_exports__getXfaPageViewport = __webpack_exports__.getXfaPageViewport;
  23783. var __webpack_exports__isDataScheme = __webpack_exports__.isDataScheme;
  23784. var __webpack_exports__isPdfFile = __webpack_exports__.isPdfFile;
  23785. var __webpack_exports__noContextMenu = __webpack_exports__.noContextMenu;
  23786. var __webpack_exports__normalizeUnicode = __webpack_exports__.normalizeUnicode;
  23787. var __webpack_exports__setLayerDimensions = __webpack_exports__.setLayerDimensions;
  23788. var __webpack_exports__shadow = __webpack_exports__.shadow;
  23789. var __webpack_exports__version = __webpack_exports__.version;
  23790. export { __webpack_exports__AbortException as AbortException, __webpack_exports__AnnotationEditorLayer as AnnotationEditorLayer, __webpack_exports__AnnotationEditorParamsType as AnnotationEditorParamsType, __webpack_exports__AnnotationEditorType as AnnotationEditorType, __webpack_exports__AnnotationEditorUIManager as AnnotationEditorUIManager, __webpack_exports__AnnotationLayer as AnnotationLayer, __webpack_exports__AnnotationMode as AnnotationMode, __webpack_exports__CMapCompressionType as CMapCompressionType, __webpack_exports__ColorPicker as ColorPicker, __webpack_exports__DOMSVGFactory as DOMSVGFactory, __webpack_exports__DrawLayer as DrawLayer, __webpack_exports__FeatureTest as FeatureTest, __webpack_exports__GlobalWorkerOptions as GlobalWorkerOptions, __webpack_exports__ImageKind as ImageKind, __webpack_exports__InvalidPDFException as InvalidPDFException, __webpack_exports__MissingPDFException as MissingPDFException, __webpack_exports__OPS as OPS, __webpack_exports__OutputScale as OutputScale, __webpack_exports__PDFDataRangeTransport as PDFDataRangeTransport, __webpack_exports__PDFDateString as PDFDateString, __webpack_exports__PDFWorker as PDFWorker, __webpack_exports__PasswordResponses as PasswordResponses, __webpack_exports__PermissionFlag as PermissionFlag, __webpack_exports__PixelsPerInch as PixelsPerInch, __webpack_exports__RenderingCancelledException as RenderingCancelledException, __webpack_exports__TextLayer as TextLayer, __webpack_exports__UnexpectedResponseException as UnexpectedResponseException, __webpack_exports__Util as Util, __webpack_exports__VerbosityLevel as VerbosityLevel, __webpack_exports__XfaLayer as XfaLayer, __webpack_exports__build as build, __webpack_exports__createValidAbsoluteUrl as createValidAbsoluteUrl, __webpack_exports__fetchData as fetchData, __webpack_exports__getDocument as getDocument, __webpack_exports__getFilenameFromUrl as getFilenameFromUrl, __webpack_exports__getPdfFilenameFromUrl as getPdfFilenameFromUrl, __webpack_exports__getXfaPageViewport as getXfaPageViewport, __webpack_exports__isDataScheme as isDataScheme, __webpack_exports__isPdfFile as isPdfFile, __webpack_exports__noContextMenu as noContextMenu, __webpack_exports__normalizeUnicode as normalizeUnicode, __webpack_exports__setLayerDimensions as setLayerDimensions, __webpack_exports__shadow as shadow, __webpack_exports__version as version };
  23791. //# sourceMappingURL=pdf.mjs.map