Document.cpp 250 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934
  1. /*
  2. * Copyright (c) 2018-2024, Andreas Kling <andreas@ladybird.org>
  3. * Copyright (c) 2021-2023, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021-2023, Luke Wilde <lukew@serenityos.org>
  5. * Copyright (c) 2021-2024, Sam Atkins <sam@ladybird.org>
  6. * Copyright (c) 2024, Matthew Olsson <mattco@serenityos.org>
  7. *
  8. * SPDX-License-Identifier: BSD-2-Clause
  9. */
  10. #include <AK/CharacterTypes.h>
  11. #include <AK/Debug.h>
  12. #include <AK/GenericLexer.h>
  13. #include <AK/InsertionSort.h>
  14. #include <AK/StringBuilder.h>
  15. #include <AK/Utf8View.h>
  16. #include <LibCore/Timer.h>
  17. #include <LibGC/RootVector.h>
  18. #include <LibJS/Runtime/Array.h>
  19. #include <LibJS/Runtime/FunctionObject.h>
  20. #include <LibJS/Runtime/NativeFunction.h>
  21. #include <LibURL/Origin.h>
  22. #include <LibURL/Parser.h>
  23. #include <LibUnicode/Segmenter.h>
  24. #include <LibWeb/Animations/Animation.h>
  25. #include <LibWeb/Animations/AnimationPlaybackEvent.h>
  26. #include <LibWeb/Animations/AnimationTimeline.h>
  27. #include <LibWeb/Animations/DocumentTimeline.h>
  28. #include <LibWeb/Bindings/DocumentPrototype.h>
  29. #include <LibWeb/Bindings/MainThreadVM.h>
  30. #include <LibWeb/Bindings/PrincipalHostDefined.h>
  31. #include <LibWeb/CSS/AnimationEvent.h>
  32. #include <LibWeb/CSS/CSSAnimation.h>
  33. #include <LibWeb/CSS/CSSImportRule.h>
  34. #include <LibWeb/CSS/CSSTransition.h>
  35. #include <LibWeb/CSS/FontFaceSet.h>
  36. #include <LibWeb/CSS/MediaQueryList.h>
  37. #include <LibWeb/CSS/MediaQueryListEvent.h>
  38. #include <LibWeb/CSS/StyleComputer.h>
  39. #include <LibWeb/CSS/StyleSheetIdentifier.h>
  40. #include <LibWeb/CSS/SystemColor.h>
  41. #include <LibWeb/CSS/TransitionEvent.h>
  42. #include <LibWeb/CSS/VisualViewport.h>
  43. #include <LibWeb/Cookie/ParsedCookie.h>
  44. #include <LibWeb/DOM/AdoptedStyleSheets.h>
  45. #include <LibWeb/DOM/Attr.h>
  46. #include <LibWeb/DOM/CDATASection.h>
  47. #include <LibWeb/DOM/Comment.h>
  48. #include <LibWeb/DOM/CustomEvent.h>
  49. #include <LibWeb/DOM/DOMImplementation.h>
  50. #include <LibWeb/DOM/Document.h>
  51. #include <LibWeb/DOM/DocumentFragment.h>
  52. #include <LibWeb/DOM/DocumentObserver.h>
  53. #include <LibWeb/DOM/DocumentType.h>
  54. #include <LibWeb/DOM/EditingHostManager.h>
  55. #include <LibWeb/DOM/Element.h>
  56. #include <LibWeb/DOM/ElementFactory.h>
  57. #include <LibWeb/DOM/Event.h>
  58. #include <LibWeb/DOM/HTMLCollection.h>
  59. #include <LibWeb/DOM/InputEventsTarget.h>
  60. #include <LibWeb/DOM/LiveNodeList.h>
  61. #include <LibWeb/DOM/NodeIterator.h>
  62. #include <LibWeb/DOM/Position.h>
  63. #include <LibWeb/DOM/ProcessingInstruction.h>
  64. #include <LibWeb/DOM/Range.h>
  65. #include <LibWeb/DOM/ShadowRoot.h>
  66. #include <LibWeb/DOM/Text.h>
  67. #include <LibWeb/DOM/TreeWalker.h>
  68. #include <LibWeb/DOM/Utils.h>
  69. #include <LibWeb/DOMURL/DOMURL.h>
  70. #include <LibWeb/Dump.h>
  71. #include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
  72. #include <LibWeb/FileAPI/BlobURLStore.h>
  73. #include <LibWeb/HTML/AttributeNames.h>
  74. #include <LibWeb/HTML/BeforeUnloadEvent.h>
  75. #include <LibWeb/HTML/BrowsingContext.h>
  76. #include <LibWeb/HTML/CustomElements/CustomElementDefinition.h>
  77. #include <LibWeb/HTML/CustomElements/CustomElementReactionNames.h>
  78. #include <LibWeb/HTML/CustomElements/CustomElementRegistry.h>
  79. #include <LibWeb/HTML/DocumentState.h>
  80. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  81. #include <LibWeb/HTML/EventNames.h>
  82. #include <LibWeb/HTML/Focus.h>
  83. #include <LibWeb/HTML/HTMLAllCollection.h>
  84. #include <LibWeb/HTML/HTMLAnchorElement.h>
  85. #include <LibWeb/HTML/HTMLAreaElement.h>
  86. #include <LibWeb/HTML/HTMLBaseElement.h>
  87. #include <LibWeb/HTML/HTMLBodyElement.h>
  88. #include <LibWeb/HTML/HTMLDocument.h>
  89. #include <LibWeb/HTML/HTMLEmbedElement.h>
  90. #include <LibWeb/HTML/HTMLFormElement.h>
  91. #include <LibWeb/HTML/HTMLFrameSetElement.h>
  92. #include <LibWeb/HTML/HTMLHeadElement.h>
  93. #include <LibWeb/HTML/HTMLHtmlElement.h>
  94. #include <LibWeb/HTML/HTMLIFrameElement.h>
  95. #include <LibWeb/HTML/HTMLImageElement.h>
  96. #include <LibWeb/HTML/HTMLInputElement.h>
  97. #include <LibWeb/HTML/HTMLLinkElement.h>
  98. #include <LibWeb/HTML/HTMLObjectElement.h>
  99. #include <LibWeb/HTML/HTMLScriptElement.h>
  100. #include <LibWeb/HTML/HTMLStyleElement.h>
  101. #include <LibWeb/HTML/HTMLTextAreaElement.h>
  102. #include <LibWeb/HTML/HTMLTitleElement.h>
  103. #include <LibWeb/HTML/HashChangeEvent.h>
  104. #include <LibWeb/HTML/ListOfAvailableImages.h>
  105. #include <LibWeb/HTML/Location.h>
  106. #include <LibWeb/HTML/MessageEvent.h>
  107. #include <LibWeb/HTML/MessagePort.h>
  108. #include <LibWeb/HTML/Navigable.h>
  109. #include <LibWeb/HTML/Navigation.h>
  110. #include <LibWeb/HTML/NavigationParams.h>
  111. #include <LibWeb/HTML/Numbers.h>
  112. #include <LibWeb/HTML/Parser/HTMLParser.h>
  113. #include <LibWeb/HTML/PopStateEvent.h>
  114. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  115. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  116. #include <LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.h>
  117. #include <LibWeb/HTML/SharedResourceRequest.h>
  118. #include <LibWeb/HTML/TraversableNavigable.h>
  119. #include <LibWeb/HTML/Window.h>
  120. #include <LibWeb/HTML/WindowProxy.h>
  121. #include <LibWeb/HighResolutionTime/Performance.h>
  122. #include <LibWeb/HighResolutionTime/TimeOrigin.h>
  123. #include <LibWeb/Infra/CharacterTypes.h>
  124. #include <LibWeb/Infra/Strings.h>
  125. #include <LibWeb/IntersectionObserver/IntersectionObserver.h>
  126. #include <LibWeb/Layout/BlockFormattingContext.h>
  127. #include <LibWeb/Layout/TreeBuilder.h>
  128. #include <LibWeb/Layout/Viewport.h>
  129. #include <LibWeb/Namespace.h>
  130. #include <LibWeb/Page/Page.h>
  131. #include <LibWeb/Painting/ViewportPaintable.h>
  132. #include <LibWeb/PermissionsPolicy/AutoplayAllowlist.h>
  133. #include <LibWeb/ResizeObserver/ResizeObserver.h>
  134. #include <LibWeb/ResizeObserver/ResizeObserverEntry.h>
  135. #include <LibWeb/SVG/SVGDecodedImageData.h>
  136. #include <LibWeb/SVG/SVGElement.h>
  137. #include <LibWeb/SVG/SVGStyleElement.h>
  138. #include <LibWeb/SVG/SVGTitleElement.h>
  139. #include <LibWeb/Selection/Selection.h>
  140. #include <LibWeb/UIEvents/CompositionEvent.h>
  141. #include <LibWeb/UIEvents/EventNames.h>
  142. #include <LibWeb/UIEvents/FocusEvent.h>
  143. #include <LibWeb/UIEvents/KeyboardEvent.h>
  144. #include <LibWeb/UIEvents/MouseEvent.h>
  145. #include <LibWeb/UIEvents/TextEvent.h>
  146. #include <LibWeb/WebIDL/AbstractOperations.h>
  147. #include <LibWeb/WebIDL/DOMException.h>
  148. #include <LibWeb/WebIDL/ExceptionOr.h>
  149. namespace Web::DOM {
  150. GC_DEFINE_ALLOCATOR(Document);
  151. // https://html.spec.whatwg.org/multipage/origin.html#obtain-browsing-context-navigation
  152. static GC::Ref<HTML::BrowsingContext> obtain_a_browsing_context_to_use_for_a_navigation_response(
  153. HTML::BrowsingContext& browsing_context,
  154. HTML::SandboxingFlagSet sandbox_flags,
  155. HTML::OpenerPolicy navigation_coop,
  156. HTML::OpenerPolicyEnforcementResult coop_enforcement_result)
  157. {
  158. // 1. If browsingContext is not a top-level browsing context, return browsingContext.
  159. if (!browsing_context.is_top_level())
  160. return browsing_context;
  161. // 2. If coopEnforcementResult's needs a browsing context group switch is false, then:
  162. if (!coop_enforcement_result.needs_a_browsing_context_group_switch) {
  163. // 1. If coopEnforcementResult's would need a browsing context group switch due to report-only is true,
  164. if (coop_enforcement_result.would_need_a_browsing_context_group_switch_due_to_report_only) {
  165. // FIXME: set browsing context's virtual browsing context group ID to a new unique identifier.
  166. }
  167. // 2. Return browsingContext.
  168. return browsing_context;
  169. }
  170. // 3. Let newBrowsingContext be the first return value of creating a new top-level browsing context and document
  171. auto new_browsing_context = HTML::create_a_new_top_level_browsing_context_and_document(browsing_context.page()).release_value_but_fixme_should_propagate_errors().browsing_context;
  172. // FIXME: 4. If navigationCOOP's value is "same-origin-plurs-COEP", then set newBrowsingContext's group's
  173. // cross-origin isolation mode to either "logical" or "concrete". The choice of which is implementation-defined.
  174. // 5. If sandboxFlags is not empty, then:
  175. if (!is_empty(sandbox_flags)) {
  176. // 1. Assert navigationCOOP's value is "unsafe-none".
  177. VERIFY(navigation_coop.value == HTML::OpenerPolicyValue::UnsafeNone);
  178. // 2. Assert: newBrowsingContext's popup sandboxing flag set is empty.
  179. VERIFY(is_empty(new_browsing_context->popup_sandboxing_flag_set()));
  180. // 3. Set newBrowsingContext's popup sandboxing flag set to a clone of sandboxFlags.
  181. new_browsing_context->set_popup_sandboxing_flag_set(sandbox_flags);
  182. }
  183. // 6. Return newBrowsingContext.
  184. return new_browsing_context;
  185. }
  186. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#initialise-the-document-object
  187. WebIDL::ExceptionOr<GC::Ref<Document>> Document::create_and_initialize(Type type, String content_type, HTML::NavigationParams const& navigation_params)
  188. {
  189. // 1. Let browsingContext be navigationParams's navigable's active browsing context.
  190. auto browsing_context = navigation_params.navigable->active_browsing_context();
  191. // 2. Set browsingContext to the result of the obtaining a browsing context to use for a navigation response given browsingContext, navigationParams's final sandboxing flag set,
  192. // navigationParams's opener policy, and navigationParams's COOP enforcement result.
  193. browsing_context = obtain_a_browsing_context_to_use_for_a_navigation_response(
  194. *browsing_context,
  195. navigation_params.final_sandboxing_flag_set,
  196. navigation_params.opener_policy,
  197. navigation_params.coop_enforcement_result);
  198. // FIXME: 3. Let permissionsPolicy be the result of creating a permissions policy from a response
  199. // given browsingContext, navigationParams's origin, and navigationParams's response.
  200. // 4. Let creationURL be navigationParams's response's URL.
  201. auto creation_url = navigation_params.response->url();
  202. // 5. If navigationParams's request is non-null, then set creationURL to navigationParams's request's current URL.
  203. if (navigation_params.request) {
  204. creation_url = navigation_params.request->current_url();
  205. }
  206. // 6. Let window be null.
  207. GC::Ptr<HTML::Window> window;
  208. // 7. If browsingContext's active document's is initial about:blank is true,
  209. // and browsingContext's active document's origin is same origin-domain with navigationParams's origin,
  210. // then set window to browsingContext's active window.
  211. // FIXME: still_on_its_initial_about_blank_document() is not in the spec anymore.
  212. // However, replacing this with the spec-mandated is_initial_about_blank() results in the browsing context
  213. // holding an incorrect active document for the replace from initial about:blank to the real document.
  214. // See #22293 for more details.
  215. if (false
  216. && (browsing_context->active_document() && browsing_context->active_document()->origin().is_same_origin(navigation_params.origin))) {
  217. window = browsing_context->active_window();
  218. }
  219. // 8. Otherwise:
  220. else {
  221. // FIXME: 1. Let oacHeader be the result of getting a structured field value given `Origin-Agent-Cluster` and "item" from response's header list.
  222. // FIXME: 2. Let requestsOAC be true if oacHeader is not null and oacHeader[0] is the boolean true; otherwise false.
  223. [[maybe_unused]] auto requests_oac = false;
  224. // FIXME: 3. If navigationParams's reserved environment is a non-secure context, then set requestsOAC to false.
  225. // FIXME: 4. Let agent be the result of obtaining a similar-origin window agent given navigationParams's origin, browsingContext's group, and requestsOAC.
  226. // 5. Let realm execution context be the result of creating a new JavaScript realm given agent and the following customizations:
  227. auto realm_execution_context = Bindings::create_a_new_javascript_realm(
  228. Bindings::main_thread_vm(),
  229. [&](JS::Realm& realm) -> JS::Object* {
  230. // - For the global object, create a new Window object.
  231. window = HTML::Window::create(realm);
  232. return window;
  233. },
  234. [&](JS::Realm&) -> JS::Object* {
  235. // - For the global this binding, use browsingContext's WindowProxy object.
  236. return browsing_context->window_proxy();
  237. });
  238. // 6. Set window to the global object of realmExecutionContext's Realm component.
  239. window = verify_cast<HTML::Window>(realm_execution_context->realm->global_object());
  240. // 7. Let topLevelCreationURL be creationURL.
  241. auto top_level_creation_url = creation_url;
  242. // 8. Let topLevelOrigin be navigationParams's origin.
  243. auto top_level_origin = navigation_params.origin;
  244. // 9. If navigable's container is not null, then:
  245. if (navigation_params.navigable->container()) {
  246. // 1. Let parentEnvironment be navigable's container's relevant settings object.
  247. auto& parent_environment = HTML::relevant_settings_object(*navigation_params.navigable->container());
  248. // 2. Set topLevelCreationURL to parentEnvironment's top-level creation URL.
  249. top_level_creation_url = parent_environment.top_level_creation_url;
  250. // 3. Set topLevelOrigin to parentEnvironment's top-level origin.
  251. top_level_origin = parent_environment.top_level_origin;
  252. }
  253. // 9. Set up a window environment settings object with creationURL, realm execution context,
  254. // navigationParams's reserved environment, topLevelCreationURL, and topLevelOrigin.
  255. // FIXME: Why do we assume `creation_url` is non-empty here? Is this a spec bug?
  256. // FIXME: Why do we assume `top_level_creation_url` is non-empty here? Is this a spec bug?
  257. HTML::WindowEnvironmentSettingsObject::setup(
  258. browsing_context->page(),
  259. creation_url.value(),
  260. move(realm_execution_context),
  261. navigation_params.reserved_environment,
  262. top_level_creation_url.value(),
  263. top_level_origin);
  264. }
  265. // FIXME: 9. Let loadTimingInfo be a new document load timing info with its navigation start time set to navigationParams's response's timing info's start time.
  266. // 10. Let document be a new Document, with
  267. // type: type
  268. // content type: contentType
  269. // origin: navigationParams's origin
  270. // browsing context: browsingContext
  271. // policy container: navigationParams's policy container
  272. // FIXME: permissions policy: permissionsPolicy
  273. // active sandboxing flag set: navigationParams's final sandboxing flag set
  274. // FIXME: opener policy: navigationParams's opener policy
  275. // FIXME: load timing info: loadTimingInfo
  276. // FIXME: was created via cross-origin redirects: navigationParams's response's has cross-origin redirects
  277. // during-loading navigation ID for WebDriver BiDi: navigationParams's id
  278. // URL: creationURL
  279. // current document readiness: "loading"
  280. // about base URL: navigationParams's about base URL
  281. // allow declarative shadow roots: true
  282. auto document = HTML::HTMLDocument::create(window->realm());
  283. document->m_type = type;
  284. document->m_content_type = move(content_type);
  285. document->set_origin(navigation_params.origin);
  286. document->set_browsing_context(browsing_context);
  287. document->m_policy_container = navigation_params.policy_container;
  288. document->m_active_sandboxing_flag_set = navigation_params.final_sandboxing_flag_set;
  289. document->m_navigation_id = navigation_params.id;
  290. document->set_url(*creation_url);
  291. document->m_readiness = HTML::DocumentReadyState::Loading;
  292. document->m_about_base_url = navigation_params.about_base_url;
  293. document->set_allow_declarative_shadow_roots(true);
  294. document->m_window = window;
  295. // NOTE: Non-standard: Pull out the Last-Modified header for use in the lastModified property.
  296. if (auto maybe_last_modified = navigation_params.response->header_list()->get("Last-Modified"sv.bytes()); maybe_last_modified.has_value())
  297. document->m_last_modified = Core::DateTime::parse("%a, %d %b %Y %H:%M:%S %Z"sv, maybe_last_modified.value());
  298. // 11. Set window's associated Document to document.
  299. window->set_associated_document(*document);
  300. // FIXME: 12. Run CSP initialization for a Document given document.
  301. // 13. If navigationParams's request is non-null, then:
  302. if (navigation_params.request) {
  303. // 1. Set document's referrer to the empty string.
  304. document->m_referrer = String {};
  305. // 2. Let referrer be navigationParams's request's referrer.
  306. auto const& referrer = navigation_params.request->referrer();
  307. // 3. If referrer is a URL record, then set document's referrer to the serialization of referrer.
  308. if (referrer.has<URL::URL>()) {
  309. document->m_referrer = referrer.get<URL::URL>().serialize();
  310. }
  311. }
  312. // FIXME: 14: If navigationParams's fetch controller is not null, then:
  313. // FIXME: 15. Create the navigation timing entry for document, with navigationParams's response's timing info, redirectCount, navigationParams's navigation timing type, and
  314. // navigationParams's response's service worker timing info.
  315. // 16. If navigationParams's response has a `Refresh` header, then:
  316. if (auto maybe_refresh = navigation_params.response->header_list()->get("Refresh"sv.bytes()); maybe_refresh.has_value()) {
  317. // 1. Let value be the isomorphic decoding of the value of the header.
  318. auto value = Infra::isomorphic_decode(maybe_refresh.value());
  319. // 2. Run the shared declarative refresh steps with document and value.
  320. document->shared_declarative_refresh_steps(value, nullptr);
  321. }
  322. // FIXME: 17. If navigationParams's commit early hints is not null, then call navigationParams's commit early hints with document.
  323. // FIXME: 18. Process link headers given document, navigationParams's response, and "pre-media".
  324. // 19. Return document.
  325. return document;
  326. }
  327. WebIDL::ExceptionOr<GC::Ref<Document>> Document::construct_impl(JS::Realm& realm)
  328. {
  329. return Document::create(realm);
  330. }
  331. GC::Ref<Document> Document::create(JS::Realm& realm, URL::URL const& url)
  332. {
  333. return realm.create<Document>(realm, url);
  334. }
  335. GC::Ref<Document> Document::create_for_fragment_parsing(JS::Realm& realm)
  336. {
  337. return realm.create<Document>(realm, "about:blank"sv, TemporaryDocumentForFragmentParsing::Yes);
  338. }
  339. Document::Document(JS::Realm& realm, const URL::URL& url, TemporaryDocumentForFragmentParsing temporary_document_for_fragment_parsing)
  340. : ParentNode(realm, *this, NodeType::DOCUMENT_NODE)
  341. , m_page(Bindings::principal_host_defined_page(realm))
  342. , m_style_computer(make<CSS::StyleComputer>(*this))
  343. , m_url(url)
  344. , m_temporary_document_for_fragment_parsing(temporary_document_for_fragment_parsing)
  345. , m_editing_host_manager(EditingHostManager::create(realm, *this))
  346. {
  347. m_legacy_platform_object_flags = PlatformObject::LegacyPlatformObjectFlags {
  348. .supports_named_properties = true,
  349. .has_legacy_override_built_ins_interface_extended_attribute = true,
  350. };
  351. m_cursor_blink_timer = Core::Timer::create_repeating(500, [this] {
  352. auto cursor_position = this->cursor_position();
  353. if (!cursor_position)
  354. return;
  355. auto node = cursor_position->node();
  356. if (!node)
  357. return;
  358. auto navigable = this->navigable();
  359. if (!navigable || !navigable->is_focused())
  360. return;
  361. node->document().update_layout();
  362. if (node->paintable()) {
  363. m_cursor_blink_state = !m_cursor_blink_state;
  364. node->paintable()->set_needs_display();
  365. }
  366. });
  367. HTML::main_thread_event_loop().register_document({}, *this);
  368. }
  369. Document::~Document()
  370. {
  371. HTML::main_thread_event_loop().unregister_document({}, *this);
  372. }
  373. void Document::initialize(JS::Realm& realm)
  374. {
  375. Base::initialize(realm);
  376. WEB_SET_PROTOTYPE_FOR_INTERFACE(Document);
  377. m_selection = realm.create<Selection::Selection>(realm, *this);
  378. m_list_of_available_images = realm.create<HTML::ListOfAvailableImages>();
  379. page().client().page_did_create_new_document(*this);
  380. }
  381. // https://html.spec.whatwg.org/multipage/document-lifecycle.html#populate-with-html/head/body
  382. WebIDL::ExceptionOr<void> Document::populate_with_html_head_and_body()
  383. {
  384. // 1. Let html be the result of creating an element given document, "html", and the HTML namespace.
  385. auto html = TRY(DOM::create_element(*this, HTML::TagNames::html, Namespace::HTML));
  386. // 2. Let head be the result of creating an element given document, "head", and the HTML namespace.
  387. auto head = TRY(DOM::create_element(*this, HTML::TagNames::head, Namespace::HTML));
  388. // 3. Let body be the result of creating an element given document, "body", and the HTML namespace.
  389. auto body = TRY(DOM::create_element(*this, HTML::TagNames::body, Namespace::HTML));
  390. // 4. Append html to document.
  391. TRY(append_child(html));
  392. // 5. Append head to html.
  393. TRY(html->append_child(head));
  394. // 6. Append body to html.
  395. TRY(html->append_child(body));
  396. return {};
  397. }
  398. void Document::visit_edges(Cell::Visitor& visitor)
  399. {
  400. Base::visit_edges(visitor);
  401. visitor.visit(m_page);
  402. visitor.visit(m_window);
  403. visitor.visit(m_layout_root);
  404. visitor.visit(m_style_sheets);
  405. visitor.visit(m_hovered_node);
  406. visitor.visit(m_inspected_node);
  407. visitor.visit(m_active_favicon);
  408. visitor.visit(m_focused_element);
  409. visitor.visit(m_active_element);
  410. visitor.visit(m_target_element);
  411. visitor.visit(m_implementation);
  412. visitor.visit(m_current_script);
  413. visitor.visit(m_associated_inert_template_document);
  414. visitor.visit(m_appropriate_template_contents_owner_document);
  415. visitor.visit(m_pending_parsing_blocking_script);
  416. visitor.visit(m_history);
  417. visitor.visit(m_browsing_context);
  418. visitor.visit(m_applets);
  419. visitor.visit(m_anchors);
  420. visitor.visit(m_images);
  421. visitor.visit(m_embeds);
  422. visitor.visit(m_links);
  423. visitor.visit(m_forms);
  424. visitor.visit(m_scripts);
  425. visitor.visit(m_all);
  426. visitor.visit(m_fonts);
  427. visitor.visit(m_selection);
  428. visitor.visit(m_first_base_element_with_href_in_tree_order);
  429. visitor.visit(m_parser);
  430. visitor.visit(m_lazy_load_intersection_observer);
  431. visitor.visit(m_visual_viewport);
  432. visitor.visit(m_latest_entry);
  433. visitor.visit(m_default_timeline);
  434. visitor.visit(m_scripts_to_execute_when_parsing_has_finished);
  435. visitor.visit(m_scripts_to_execute_in_order_as_soon_as_possible);
  436. visitor.visit(m_scripts_to_execute_as_soon_as_possible);
  437. visitor.visit(m_node_iterators);
  438. visitor.visit(m_document_observers);
  439. visitor.visit(m_document_observers_being_notified);
  440. visitor.visit(m_pending_scroll_event_targets);
  441. visitor.visit(m_pending_scrollend_event_targets);
  442. visitor.visit(m_resize_observers);
  443. visitor.visit(m_shared_resource_requests);
  444. visitor.visit(m_associated_animation_timelines);
  445. visitor.visit(m_list_of_available_images);
  446. for (auto* form_associated_element : m_form_associated_elements_with_form_attribute)
  447. visitor.visit(form_associated_element->form_associated_element_to_html_element());
  448. visitor.visit(m_potentially_named_elements);
  449. for (auto& event : m_pending_animation_event_queue) {
  450. visitor.visit(event.event);
  451. visitor.visit(event.animation);
  452. visitor.visit(event.target);
  453. }
  454. visitor.visit(m_adopted_style_sheets);
  455. visitor.visit(m_shadow_roots);
  456. visitor.visit(m_top_layer_elements);
  457. visitor.visit(m_top_layer_pending_removals);
  458. visitor.visit(m_console_client);
  459. visitor.visit(m_editing_host_manager);
  460. }
  461. // https://w3c.github.io/selection-api/#dom-document-getselection
  462. GC::Ptr<Selection::Selection> Document::get_selection() const
  463. {
  464. // The method must return the selection associated with this if this has an associated browsing context,
  465. // and it must return null otherwise.
  466. if (!browsing_context())
  467. return {};
  468. return m_selection;
  469. }
  470. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-write
  471. WebIDL::ExceptionOr<void> Document::write(Vector<String> const& strings)
  472. {
  473. StringBuilder builder;
  474. builder.join(""sv, strings);
  475. return run_the_document_write_steps(builder.string_view());
  476. }
  477. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-writeln
  478. WebIDL::ExceptionOr<void> Document::writeln(Vector<String> const& strings)
  479. {
  480. StringBuilder builder;
  481. builder.join(""sv, strings);
  482. builder.append("\n"sv);
  483. return run_the_document_write_steps(builder.string_view());
  484. }
  485. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#document-write-steps
  486. WebIDL::ExceptionOr<void> Document::run_the_document_write_steps(StringView input)
  487. {
  488. // 1. If document is an XML document, then throw an "InvalidStateError" DOMException.
  489. if (m_type == Type::XML)
  490. return WebIDL::InvalidStateError::create(realm(), "write() called on XML document."_string);
  491. // 2. If document's throw-on-dynamic-markup-insertion counter is greater than 0, then throw an "InvalidStateError" DOMException.
  492. if (m_throw_on_dynamic_markup_insertion_counter > 0)
  493. return WebIDL::InvalidStateError::create(realm(), "throw-on-dynamic-markup-insertion-counter greater than zero."_string);
  494. // 3. If document's active parser was aborted is true, then return.
  495. if (m_active_parser_was_aborted)
  496. return {};
  497. // 4. If the insertion point is undefined, then:
  498. if (!(m_parser && m_parser->tokenizer().is_insertion_point_defined())) {
  499. // 1. If document's unload counter is greater than 0 or document's ignore-destructive-writes counter is greater than 0, then return.
  500. if (m_unload_counter > 0 || m_ignore_destructive_writes_counter > 0)
  501. return {};
  502. // 2. Run the document open steps with document.
  503. TRY(open());
  504. }
  505. // 5. Insert input into the input stream just before the insertion point.
  506. m_parser->tokenizer().insert_input_at_insertion_point(input);
  507. // 6. If there is no pending parsing-blocking script, have the HTML parser process input, one code point at a time,
  508. // processing resulting tokens as they are emitted, and stopping when the tokenizer reaches the insertion point
  509. // or when the processing of the tokenizer is aborted by the tree construction stage (this can happen if a script
  510. // end tag token is emitted by the tokenizer).
  511. if (!pending_parsing_blocking_script())
  512. m_parser->run(HTML::HTMLTokenizer::StopAtInsertionPoint::Yes);
  513. return {};
  514. }
  515. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-open
  516. WebIDL::ExceptionOr<Document*> Document::open(Optional<String> const&, Optional<String> const&)
  517. {
  518. // If document belongs to a child navigable, we need to make sure its initial navigation is done,
  519. // because subsequent steps will modify "initial about:blank" to false, which would cause
  520. // initial navigation to fail in case it was "about:blank".
  521. if (auto navigable = this->navigable(); navigable && navigable->container() && !navigable->container()->content_navigable_initialized()) {
  522. HTML::main_thread_event_loop().spin_processing_tasks_with_source_until(HTML::Task::Source::NavigationAndTraversal, GC::create_function(heap(), [navigable_container = navigable->container()] {
  523. return navigable_container->content_navigable_initialized();
  524. }));
  525. }
  526. // 1. If document is an XML document, then throw an "InvalidStateError" DOMException exception.
  527. if (m_type == Type::XML)
  528. return WebIDL::InvalidStateError::create(realm(), "open() called on XML document."_string);
  529. // 2. If document's throw-on-dynamic-markup-insertion counter is greater than 0, then throw an "InvalidStateError" DOMException.
  530. if (m_throw_on_dynamic_markup_insertion_counter > 0)
  531. return WebIDL::InvalidStateError::create(realm(), "throw-on-dynamic-markup-insertion-counter greater than zero."_string);
  532. // FIXME: 3. Let entryDocument be the entry global object's associated Document.
  533. auto& entry_document = *this;
  534. // 4. If document's origin is not same origin to entryDocument's origin, then throw a "SecurityError" DOMException.
  535. if (origin() != entry_document.origin())
  536. return WebIDL::SecurityError::create(realm(), "Document.origin() not the same as entryDocument's."_string);
  537. // 5. If document has an active parser whose script nesting level is greater than 0, then return document.
  538. if (m_parser && m_parser->script_nesting_level() > 0)
  539. return this;
  540. // 6. Similarly, if document's unload counter is greater than 0, then return document.
  541. if (m_unload_counter > 0)
  542. return this;
  543. // 7. If document's active parser was aborted is true, then return document.
  544. if (m_active_parser_was_aborted)
  545. return this;
  546. // FIXME: 8. If document's browsing context is non-null and there is an existing attempt to navigate document's browsing context, then stop document loading given document.
  547. // FIXME: 9. For each shadow-including inclusive descendant node of document, erase all event listeners and handlers given node.
  548. // FIXME 10. If document is the associated Document of document's relevant global object, then erase all event listeners and handlers given document's relevant global object.
  549. // 11. Replace all with null within document, without firing any mutation events.
  550. replace_all(nullptr);
  551. // 12. If document is fully active, then:
  552. if (is_fully_active()) {
  553. // 1. Let newURL be a copy of entryDocument's URL.
  554. auto new_url = entry_document.url();
  555. // 2. If entryDocument is not document, then set newURL's fragment to null.
  556. if (&entry_document != this)
  557. new_url.set_fragment({});
  558. // FIXME: 3. Run the URL and history update steps with document and newURL.
  559. }
  560. // 13. Set document's is initial about:blank to false.
  561. set_is_initial_about_blank(false);
  562. // FIXME: 14. If document's iframe load in progress flag is set, then set document's mute iframe load flag.
  563. // 15. Set document to no-quirks mode.
  564. set_quirks_mode(QuirksMode::No);
  565. // 16. Create a new HTML parser and associate it with document. This is a script-created parser (meaning that it can be closed by the document.open() and document.close() methods, and that the tokenizer will wait for an explicit call to document.close() before emitting an end-of-file token). The encoding confidence is irrelevant.
  566. m_parser = HTML::HTMLParser::create_for_scripting(*this);
  567. // 17. Set the insertion point to point at just before the end of the input stream (which at this point will be empty).
  568. m_parser->tokenizer().update_insertion_point();
  569. // 18. Update the current document readiness of document to "loading".
  570. update_readiness(HTML::DocumentReadyState::Loading);
  571. // 19. Return document.
  572. return this;
  573. }
  574. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-open-window
  575. WebIDL::ExceptionOr<GC::Ptr<HTML::WindowProxy>> Document::open(StringView url, StringView name, StringView features)
  576. {
  577. // 1. If this is not fully active, then throw an "InvalidAccessError" DOMException exception.
  578. if (!is_fully_active())
  579. return WebIDL::InvalidAccessError::create(realm(), "Cannot perform open on a document that isn't fully active."_string);
  580. // 2. Return the result of running the window open steps with url, name, and features.
  581. return window()->window_open_steps(url, name, features);
  582. }
  583. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#closing-the-input-stream
  584. WebIDL::ExceptionOr<void> Document::close()
  585. {
  586. // 1. If document is an XML document, then throw an "InvalidStateError" DOMException exception.
  587. if (m_type == Type::XML)
  588. return WebIDL::InvalidStateError::create(realm(), "close() called on XML document."_string);
  589. // 2. If document's throw-on-dynamic-markup-insertion counter is greater than 0, then throw an "InvalidStateError" DOMException.
  590. if (m_throw_on_dynamic_markup_insertion_counter > 0)
  591. return WebIDL::InvalidStateError::create(realm(), "throw-on-dynamic-markup-insertion-counter greater than zero."_string);
  592. // 3. If there is no script-created parser associated with the document, then return.
  593. if (!m_parser)
  594. return {};
  595. // 4. Insert an explicit "EOF" character at the end of the parser's input stream.
  596. m_parser->tokenizer().insert_eof();
  597. // 5. If there is a pending parsing-blocking script, then return.
  598. if (pending_parsing_blocking_script())
  599. return {};
  600. // 6. Run the tokenizer, processing resulting tokens as they are emitted, and stopping when the tokenizer reaches the explicit "EOF" character or spins the event loop.
  601. m_parser->run();
  602. // AD-HOC: This ensures that a load event is fired if the node navigable's container is an iframe.
  603. completely_finish_loading();
  604. return {};
  605. }
  606. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-document-defaultview
  607. GC::Ptr<HTML::WindowProxy> Document::default_view()
  608. {
  609. // If this's browsing context is null, then return null.
  610. if (!browsing_context())
  611. return {};
  612. // 2. Return this's browsing context's WindowProxy object.
  613. return browsing_context()->window_proxy();
  614. }
  615. GC::Ptr<HTML::WindowProxy const> Document::default_view() const
  616. {
  617. return const_cast<Document*>(this)->default_view();
  618. }
  619. URL::Origin Document::origin() const
  620. {
  621. return m_origin;
  622. }
  623. void Document::set_origin(URL::Origin const& origin)
  624. {
  625. m_origin = origin;
  626. }
  627. void Document::schedule_style_update()
  628. {
  629. if (!browsing_context())
  630. return;
  631. // NOTE: Update of the style is a step in HTML event loop processing.
  632. HTML::main_thread_event_loop().schedule();
  633. }
  634. void Document::schedule_layout_update()
  635. {
  636. if (!browsing_context())
  637. return;
  638. // NOTE: Update of the layout is a step in HTML event loop processing.
  639. HTML::main_thread_event_loop().schedule();
  640. }
  641. bool Document::is_child_allowed(Node const& node) const
  642. {
  643. switch (node.type()) {
  644. case NodeType::DOCUMENT_NODE:
  645. case NodeType::TEXT_NODE:
  646. return false;
  647. case NodeType::COMMENT_NODE:
  648. return true;
  649. case NodeType::DOCUMENT_TYPE_NODE:
  650. return !first_child_of_type<DocumentType>();
  651. case NodeType::ELEMENT_NODE:
  652. return !first_child_of_type<Element>();
  653. default:
  654. return false;
  655. }
  656. }
  657. Element* Document::document_element()
  658. {
  659. return first_child_of_type<Element>();
  660. }
  661. Element const* Document::document_element() const
  662. {
  663. return first_child_of_type<Element>();
  664. }
  665. // https://html.spec.whatwg.org/multipage/dom.html#the-html-element-2
  666. HTML::HTMLHtmlElement* Document::html_element()
  667. {
  668. // The html element of a document is its document element, if it's an html element, and null otherwise.
  669. auto* html = document_element();
  670. if (is<HTML::HTMLHtmlElement>(html))
  671. return verify_cast<HTML::HTMLHtmlElement>(html);
  672. return nullptr;
  673. }
  674. // https://html.spec.whatwg.org/multipage/dom.html#the-head-element-2
  675. HTML::HTMLHeadElement* Document::head()
  676. {
  677. // The head element of a document is the first head element that is a child of the html element, if there is one,
  678. // or null otherwise.
  679. auto* html = html_element();
  680. if (!html)
  681. return nullptr;
  682. return html->first_child_of_type<HTML::HTMLHeadElement>();
  683. }
  684. // https://html.spec.whatwg.org/multipage/dom.html#the-title-element-2
  685. GC::Ptr<HTML::HTMLTitleElement> Document::title_element()
  686. {
  687. // The title element of a document is the first title element in the document (in tree order), if there is one, or
  688. // null otherwise.
  689. GC::Ptr<HTML::HTMLTitleElement> title_element = nullptr;
  690. for_each_in_subtree_of_type<HTML::HTMLTitleElement>([&](auto& title_element_in_tree) {
  691. title_element = title_element_in_tree;
  692. return TraversalDecision::Break;
  693. });
  694. return title_element;
  695. }
  696. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-dir
  697. StringView Document::dir() const
  698. {
  699. // The dir IDL attribute on Document objects must reflect the dir content attribute of the html
  700. // element, if any, limited to only known values. If there is no such element, then the
  701. // attribute must return the empty string and do nothing on setting.
  702. if (auto html = html_element())
  703. return html->dir();
  704. return ""sv;
  705. }
  706. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-dir
  707. void Document::set_dir(String const& dir)
  708. {
  709. // The dir IDL attribute on Document objects must reflect the dir content attribute of the html
  710. // element, if any, limited to only known values. If there is no such element, then the
  711. // attribute must return the empty string and do nothing on setting.
  712. if (auto html = html_element())
  713. html->set_dir(dir);
  714. }
  715. // https://html.spec.whatwg.org/multipage/dom.html#the-body-element-2
  716. HTML::HTMLElement* Document::body()
  717. {
  718. // The body element of a document is the first of the html element's children that is either
  719. // a body element or a frameset element, or null if there is no such element.
  720. auto* html = html_element();
  721. if (!html)
  722. return nullptr;
  723. for (auto* child = html->first_child(); child; child = child->next_sibling()) {
  724. if (is<HTML::HTMLBodyElement>(*child) || is<HTML::HTMLFrameSetElement>(*child))
  725. return static_cast<HTML::HTMLElement*>(child);
  726. }
  727. return nullptr;
  728. }
  729. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-body
  730. WebIDL::ExceptionOr<void> Document::set_body(HTML::HTMLElement* new_body)
  731. {
  732. if (!is<HTML::HTMLBodyElement>(new_body) && !is<HTML::HTMLFrameSetElement>(new_body))
  733. return WebIDL::HierarchyRequestError::create(realm(), "Invalid document body element, must be 'body' or 'frameset'"_string);
  734. auto* existing_body = body();
  735. if (existing_body) {
  736. (void)TRY(existing_body->parent()->replace_child(*new_body, *existing_body));
  737. return {};
  738. }
  739. auto* document_element = this->document_element();
  740. if (!document_element)
  741. return WebIDL::HierarchyRequestError::create(realm(), "Missing document element"_string);
  742. (void)TRY(document_element->append_child(*new_body));
  743. return {};
  744. }
  745. // https://html.spec.whatwg.org/multipage/dom.html#document.title
  746. String Document::title() const
  747. {
  748. String value;
  749. // 1. If the document element is an SVG svg element, then let value be the child text content of the first SVG title
  750. // element that is a child of the document element.
  751. if (auto const* document_element = this->document_element(); is<SVG::SVGElement>(document_element)) {
  752. if (auto const* title_element = document_element->first_child_of_type<SVG::SVGTitleElement>())
  753. value = title_element->child_text_content();
  754. }
  755. // 2. Otherwise, let value be the child text content of the title element, or the empty string if the title element
  756. // is null.
  757. else if (auto title_element = this->title_element()) {
  758. value = title_element->text_content().value_or(String {});
  759. }
  760. // 3. Strip and collapse ASCII whitespace in value.
  761. auto title = Infra::strip_and_collapse_whitespace(value).release_value_but_fixme_should_propagate_errors();
  762. // 4. Return value.
  763. return title;
  764. }
  765. // https://html.spec.whatwg.org/multipage/dom.html#document.title
  766. WebIDL::ExceptionOr<void> Document::set_title(String const& title)
  767. {
  768. auto* document_element = this->document_element();
  769. // -> If the document element is an SVG svg element
  770. if (is<SVG::SVGElement>(document_element)) {
  771. GC::Ptr<Element> element;
  772. // 1. If there is an SVG title element that is a child of the document element, let element be the first such
  773. // element.
  774. if (auto* title_element = document_element->first_child_of_type<SVG::SVGTitleElement>()) {
  775. element = title_element;
  776. }
  777. // 2. Otherwise:
  778. else {
  779. // 1. Let element be the result of creating an element given the document element's node document, "title",
  780. // and the SVG namespace.
  781. element = TRY(DOM::create_element(*this, HTML::TagNames::title, Namespace::SVG));
  782. // 2. Insert element as the first child of the document element.
  783. document_element->insert_before(*element, document_element->first_child());
  784. }
  785. // 3. String replace all with the given value within element.
  786. element->string_replace_all(title);
  787. }
  788. // -> If the document element is in the HTML namespace
  789. else if (document_element && document_element->namespace_uri() == Namespace::HTML) {
  790. auto title_element = this->title_element();
  791. auto* head_element = this->head();
  792. // 1. If the title element is null and the head element is null, then return.
  793. if (title_element == nullptr && head_element == nullptr)
  794. return {};
  795. GC::Ptr<Element> element;
  796. // 2. If the title element is non-null, let element be the title element.
  797. if (title_element) {
  798. element = title_element;
  799. }
  800. // 3. Otherwise:
  801. else {
  802. // 1. Let element be the result of creating an element given the document element's node document, "title",
  803. // and the HTML namespace.
  804. element = TRY(DOM::create_element(*this, HTML::TagNames::title, Namespace::HTML));
  805. // 2. Append element to the head element.
  806. TRY(head_element->append_child(*element));
  807. }
  808. // 4. String replace all with the given value within element.
  809. element->string_replace_all(title);
  810. }
  811. // -> Otherwise
  812. else {
  813. // Do nothing.
  814. return {};
  815. }
  816. if (browsing_context() == &page().top_level_browsing_context())
  817. page().client().page_did_change_title(title.to_byte_string());
  818. return {};
  819. }
  820. void Document::tear_down_layout_tree()
  821. {
  822. m_layout_root = nullptr;
  823. m_paintable = nullptr;
  824. }
  825. Color Document::background_color() const
  826. {
  827. // CSS2 says we should use the HTML element's background color unless it's transparent...
  828. if (auto* html_element = this->html_element(); html_element && html_element->layout_node()) {
  829. auto color = html_element->layout_node()->computed_values().background_color();
  830. if (color.alpha())
  831. return color;
  832. }
  833. // ...in which case we use the BODY element's background color.
  834. if (auto* body_element = body(); body_element && body_element->layout_node()) {
  835. auto color = body_element->layout_node()->computed_values().background_color();
  836. return color;
  837. }
  838. // By default, the document is transparent.
  839. // The outermost canvas is colored by the PageHost.
  840. return Color::Transparent;
  841. }
  842. Vector<CSS::BackgroundLayerData> const* Document::background_layers() const
  843. {
  844. auto* body_element = body();
  845. if (!body_element)
  846. return {};
  847. auto body_layout_node = body_element->layout_node();
  848. if (!body_layout_node)
  849. return {};
  850. return &body_layout_node->background_layers();
  851. }
  852. void Document::update_base_element(Badge<HTML::HTMLBaseElement>)
  853. {
  854. GC::Ptr<HTML::HTMLBaseElement const> base_element;
  855. for_each_in_subtree_of_type<HTML::HTMLBaseElement>([&base_element](HTML::HTMLBaseElement const& base_element_in_tree) {
  856. if (base_element_in_tree.has_attribute(HTML::AttributeNames::href)) {
  857. base_element = &base_element_in_tree;
  858. return TraversalDecision::Break;
  859. }
  860. return TraversalDecision::Continue;
  861. });
  862. m_first_base_element_with_href_in_tree_order = base_element;
  863. }
  864. GC::Ptr<HTML::HTMLBaseElement const> Document::first_base_element_with_href_in_tree_order() const
  865. {
  866. return m_first_base_element_with_href_in_tree_order;
  867. }
  868. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#fallback-base-url
  869. URL::URL Document::fallback_base_url() const
  870. {
  871. // 1. If document is an iframe srcdoc document, then:
  872. if (HTML::url_matches_about_srcdoc(m_url)) {
  873. // 1. Assert: document's about base URL is non-null.
  874. VERIFY(m_about_base_url.has_value());
  875. // 2. Return document's about base URL.
  876. return m_about_base_url.value();
  877. }
  878. // 2. If document's URL matches about:blank and document's about base URL is non-null, then return document's about base URL.
  879. if (HTML::url_matches_about_blank(m_url) && m_about_base_url.has_value())
  880. return m_about_base_url.value();
  881. // 3. Return document's URL.
  882. return m_url;
  883. }
  884. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#document-base-url
  885. URL::URL Document::base_url() const
  886. {
  887. // 1. If there is no base element that has an href attribute in the Document, then return the Document's fallback base URL.
  888. auto base_element = first_base_element_with_href_in_tree_order();
  889. if (!base_element)
  890. return fallback_base_url();
  891. // 2. Otherwise, return the frozen base URL of the first base element in the Document that has an href attribute, in tree order.
  892. return base_element->frozen_base_url();
  893. }
  894. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#parse-a-url
  895. URL::URL Document::parse_url(StringView url) const
  896. {
  897. // 1. Let baseURL be environment's base URL, if environment is a Document object; otherwise environment's API base URL.
  898. auto base_url = this->base_url();
  899. // 2. Return the result of applying the URL parser to url, with baseURL.
  900. return DOMURL::parse(url, base_url);
  901. }
  902. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#encoding-parsing-a-url
  903. URL::URL Document::encoding_parse_url(StringView url) const
  904. {
  905. // 1. Let encoding be UTF-8.
  906. // 2. If environment is a Document object, then set encoding to environment's character encoding.
  907. auto encoding = encoding_or_default();
  908. // 3. Otherwise, if environment's relevant global object is a Window object, set encoding to environment's relevant
  909. // global object's associated Document's character encoding.
  910. // 4. Let baseURL be environment's base URL, if environment is a Document object; otherwise environment's API base URL.
  911. auto base_url = this->base_url();
  912. // 5. Return the result of applying the URL parser to url, with baseURL and encoding.
  913. return DOMURL::parse(url, base_url, encoding);
  914. }
  915. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#encoding-parsing-and-serializing-a-url
  916. Optional<String> Document::encoding_parse_and_serialize_url(StringView url) const
  917. {
  918. // 1. Let url be the result of encoding-parsing a URL given url, relative to environment.
  919. auto parsed_url = encoding_parse_url(url);
  920. // 2. If url is failure, then return failure.
  921. if (!parsed_url.is_valid())
  922. return {};
  923. // 3. Return the result of applying the URL serializer to url.
  924. return parsed_url.serialize();
  925. }
  926. void Document::set_needs_layout()
  927. {
  928. if (m_needs_layout)
  929. return;
  930. m_needs_layout = true;
  931. schedule_layout_update();
  932. }
  933. void Document::invalidate_layout_tree()
  934. {
  935. tear_down_layout_tree();
  936. schedule_layout_update();
  937. }
  938. static void propagate_scrollbar_width_to_viewport(Element& root_element, Layout::Viewport& viewport)
  939. {
  940. // https://drafts.csswg.org/css-scrollbars/#scrollbar-width
  941. // UAs must apply the scrollbar-color value set on the root element to the viewport.
  942. auto& viewport_computed_values = viewport.mutable_computed_values();
  943. auto& root_element_computed_values = root_element.layout_node()->computed_values();
  944. viewport_computed_values.set_scrollbar_width(root_element_computed_values.scrollbar_width());
  945. }
  946. static void propagate_overflow_to_viewport(Element& root_element, Layout::Viewport& viewport)
  947. {
  948. // https://drafts.csswg.org/css-overflow-3/#overflow-propagation
  949. // UAs must apply the overflow-* values set on the root element to the viewport
  950. // when the root element’s display value is not none.
  951. auto overflow_origin_node = root_element.layout_node();
  952. auto& viewport_computed_values = viewport.mutable_computed_values();
  953. // However, when the root element is an [HTML] html element (including XML syntax for HTML)
  954. // whose overflow value is visible (in both axes), and that element has as a child
  955. // a body element whose display value is also not none,
  956. // user agents must instead apply the overflow-* values of the first such child element to the viewport.
  957. if (root_element.is_html_html_element()) {
  958. auto root_element_layout_node = root_element.layout_node();
  959. auto& root_element_computed_values = root_element_layout_node->mutable_computed_values();
  960. if (root_element_computed_values.overflow_x() == CSS::Overflow::Visible && root_element_computed_values.overflow_y() == CSS::Overflow::Visible) {
  961. auto* body_element = root_element.first_child_of_type<HTML::HTMLBodyElement>();
  962. if (body_element && body_element->layout_node())
  963. overflow_origin_node = body_element->layout_node();
  964. }
  965. }
  966. // NOTE: This is where we assign the chosen overflow values to the viewport.
  967. auto& overflow_origin_computed_values = overflow_origin_node->mutable_computed_values();
  968. viewport_computed_values.set_overflow_x(overflow_origin_computed_values.overflow_x());
  969. viewport_computed_values.set_overflow_y(overflow_origin_computed_values.overflow_y());
  970. // The element from which the value is propagated must then have a used overflow value of visible.
  971. overflow_origin_computed_values.set_overflow_x(CSS::Overflow::Visible);
  972. overflow_origin_computed_values.set_overflow_y(CSS::Overflow::Visible);
  973. }
  974. void Document::update_layout()
  975. {
  976. auto navigable = this->navigable();
  977. if (!navigable || navigable->active_document() != this)
  978. return;
  979. // NOTE: If our parent document needs a relayout, we must do that *first*.
  980. // This is necessary as the parent layout may cause our viewport to change.
  981. if (navigable->container() && &navigable->container()->document() != this)
  982. navigable->container()->document().update_layout();
  983. update_style();
  984. if (!m_needs_layout && m_layout_root)
  985. return;
  986. // NOTE: If this is a document hosting <template> contents, layout is unnecessary.
  987. if (m_created_for_appropriate_template_contents)
  988. return;
  989. invalidate_display_list();
  990. auto* document_element = this->document_element();
  991. auto viewport_rect = navigable->viewport_rect();
  992. if (!m_layout_root) {
  993. Layout::TreeBuilder tree_builder;
  994. m_layout_root = verify_cast<Layout::Viewport>(*tree_builder.build(*this));
  995. if (document_element && document_element->layout_node()) {
  996. propagate_overflow_to_viewport(*document_element, *m_layout_root);
  997. propagate_scrollbar_width_to_viewport(*document_element, *m_layout_root);
  998. }
  999. }
  1000. // Assign each box that establishes a formatting context a list of absolutely positioned children it should take care of during layout
  1001. m_layout_root->for_each_in_inclusive_subtree_of_type<Layout::Box>([&](auto& child) {
  1002. child.clear_contained_abspos_children();
  1003. return TraversalDecision::Continue;
  1004. });
  1005. m_layout_root->for_each_in_inclusive_subtree([&](auto& child) {
  1006. if (!child.is_absolutely_positioned())
  1007. return TraversalDecision::Continue;
  1008. if (auto* containing_block = child.containing_block()) {
  1009. auto* closest_box_that_establishes_formatting_context = containing_block;
  1010. while (closest_box_that_establishes_formatting_context) {
  1011. if (closest_box_that_establishes_formatting_context == m_layout_root)
  1012. break;
  1013. if (Layout::FormattingContext::formatting_context_type_created_by_box(*closest_box_that_establishes_formatting_context).has_value()) {
  1014. break;
  1015. }
  1016. closest_box_that_establishes_formatting_context = closest_box_that_establishes_formatting_context->containing_block();
  1017. }
  1018. VERIFY(closest_box_that_establishes_formatting_context);
  1019. closest_box_that_establishes_formatting_context->add_contained_abspos_child(child);
  1020. }
  1021. return TraversalDecision::Continue;
  1022. });
  1023. Layout::LayoutState layout_state;
  1024. {
  1025. Layout::BlockFormattingContext root_formatting_context(layout_state, Layout::LayoutMode::Normal, *m_layout_root, nullptr);
  1026. auto& viewport = static_cast<Layout::Viewport&>(*m_layout_root);
  1027. auto& viewport_state = layout_state.get_mutable(viewport);
  1028. viewport_state.set_content_width(viewport_rect.width());
  1029. viewport_state.set_content_height(viewport_rect.height());
  1030. if (document_element && document_element->layout_node()) {
  1031. auto& icb_state = layout_state.get_mutable(verify_cast<Layout::NodeWithStyleAndBoxModelMetrics>(*document_element->layout_node()));
  1032. icb_state.set_content_width(viewport_rect.width());
  1033. }
  1034. root_formatting_context.run(
  1035. Layout::AvailableSpace(
  1036. Layout::AvailableSize::make_definite(viewport_rect.width()),
  1037. Layout::AvailableSize::make_definite(viewport_rect.height())));
  1038. }
  1039. layout_state.commit(*m_layout_root);
  1040. // Broadcast the current viewport rect to any new paintables, so they know whether they're visible or not.
  1041. inform_all_viewport_clients_about_the_current_viewport_rect();
  1042. m_document->set_needs_display();
  1043. set_needs_to_resolve_paint_only_properties();
  1044. paintable()->assign_scroll_frames();
  1045. // assign_clip_frames() needs border-radius be resolved
  1046. update_paint_and_hit_testing_properties_if_needed();
  1047. paintable()->assign_clip_frames();
  1048. if (navigable->is_traversable()) {
  1049. page().client().page_did_layout();
  1050. }
  1051. if (auto range = get_selection()->range()) {
  1052. paintable()->recompute_selection_states(*range);
  1053. }
  1054. m_needs_layout = false;
  1055. // Scrolling by zero offset will clamp scroll offset back to valid range if it was out of bounds
  1056. // after the viewport size change.
  1057. if (auto window = this->window())
  1058. window->scroll_by(0, 0);
  1059. }
  1060. [[nodiscard]] static CSS::RequiredInvalidationAfterStyleChange update_style_recursively(Node& node, CSS::StyleComputer& style_computer)
  1061. {
  1062. bool const needs_full_style_update = node.document().needs_full_style_update();
  1063. CSS::RequiredInvalidationAfterStyleChange invalidation;
  1064. if (node.is_element())
  1065. style_computer.push_ancestor(static_cast<Element const&>(node));
  1066. // NOTE: If the current node has `display:none`, we can disregard all invalidation
  1067. // caused by its children, as they will not be rendered anyway.
  1068. // We will still recompute style for the children, though.
  1069. bool is_display_none = false;
  1070. if (is<Element>(node)) {
  1071. if (needs_full_style_update || node.needs_style_update()) {
  1072. invalidation |= static_cast<Element&>(node).recompute_style();
  1073. } else if (node.needs_inherited_style_update()) {
  1074. invalidation |= static_cast<Element&>(node).recompute_inherited_style();
  1075. }
  1076. is_display_none = static_cast<Element&>(node).computed_properties()->display().is_none();
  1077. }
  1078. node.set_needs_style_update(false);
  1079. node.set_needs_inherited_style_update(false);
  1080. if (needs_full_style_update || node.child_needs_style_update()) {
  1081. if (node.is_element()) {
  1082. if (auto shadow_root = static_cast<DOM::Element&>(node).shadow_root()) {
  1083. if (needs_full_style_update || shadow_root->needs_style_update() || shadow_root->child_needs_style_update()) {
  1084. auto subtree_invalidation = update_style_recursively(*shadow_root, style_computer);
  1085. if (!is_display_none)
  1086. invalidation |= subtree_invalidation;
  1087. }
  1088. }
  1089. }
  1090. node.for_each_child([&](auto& child) {
  1091. if (needs_full_style_update || child.needs_style_update() || child.needs_inherited_style_update() || child.child_needs_style_update()) {
  1092. auto subtree_invalidation = update_style_recursively(child, style_computer);
  1093. if (!is_display_none)
  1094. invalidation |= subtree_invalidation;
  1095. }
  1096. return IterationDecision::Continue;
  1097. });
  1098. }
  1099. node.set_child_needs_style_update(false);
  1100. if (node.is_element())
  1101. style_computer.pop_ancestor(static_cast<Element const&>(node));
  1102. return invalidation;
  1103. }
  1104. void Document::update_style()
  1105. {
  1106. if (!browsing_context())
  1107. return;
  1108. update_animated_style_if_needed();
  1109. // Associated with each top-level browsing context is a current transition generation that is incremented on each
  1110. // style change event. [CSS-Transitions-2]
  1111. m_transition_generation++;
  1112. if (!needs_full_style_update() && !needs_style_update() && !child_needs_style_update())
  1113. return;
  1114. // NOTE: If this is a document hosting <template> contents, style update is unnecessary.
  1115. if (m_created_for_appropriate_template_contents)
  1116. return;
  1117. // Fetch the viewport rect once, instead of repeatedly, during style computation.
  1118. style_computer().set_viewport_rect({}, viewport_rect());
  1119. evaluate_media_rules();
  1120. style_computer().reset_ancestor_filter();
  1121. auto invalidation = update_style_recursively(*this, style_computer());
  1122. if (!invalidation.is_none()) {
  1123. invalidate_display_list();
  1124. }
  1125. if (invalidation.rebuild_layout_tree) {
  1126. invalidate_layout_tree();
  1127. } else {
  1128. if (invalidation.relayout)
  1129. set_needs_layout();
  1130. if (invalidation.rebuild_stacking_context_tree)
  1131. invalidate_stacking_context_tree();
  1132. }
  1133. m_needs_full_style_update = false;
  1134. }
  1135. void Document::update_animated_style_if_needed()
  1136. {
  1137. if (!m_needs_animated_style_update)
  1138. return;
  1139. invalidate_display_list();
  1140. for (auto& timeline : m_associated_animation_timelines) {
  1141. for (auto& animation : timeline->associated_animations()) {
  1142. if (auto effect = animation->effect(); effect && effect->target())
  1143. effect->target()->reset_animated_css_properties();
  1144. }
  1145. for (auto& animation : timeline->associated_animations()) {
  1146. if (auto effect = animation->effect())
  1147. effect->update_computed_properties();
  1148. }
  1149. }
  1150. m_needs_animated_style_update = false;
  1151. }
  1152. void Document::update_paint_and_hit_testing_properties_if_needed()
  1153. {
  1154. if (auto* paintable = this->paintable()) {
  1155. paintable->refresh_scroll_state();
  1156. }
  1157. if (!m_needs_to_resolve_paint_only_properties)
  1158. return;
  1159. m_needs_to_resolve_paint_only_properties = false;
  1160. if (auto* paintable = this->paintable()) {
  1161. paintable->resolve_paint_only_properties();
  1162. }
  1163. }
  1164. void Document::set_normal_link_color(Color color)
  1165. {
  1166. m_normal_link_color = color;
  1167. }
  1168. void Document::set_active_link_color(Color color)
  1169. {
  1170. m_active_link_color = color;
  1171. }
  1172. void Document::set_visited_link_color(Color color)
  1173. {
  1174. m_visited_link_color = color;
  1175. }
  1176. Layout::Viewport const* Document::layout_node() const
  1177. {
  1178. return static_cast<Layout::Viewport const*>(Node::layout_node());
  1179. }
  1180. Layout::Viewport* Document::layout_node()
  1181. {
  1182. return static_cast<Layout::Viewport*>(Node::layout_node());
  1183. }
  1184. void Document::set_inspected_node(Node* node, Optional<CSS::Selector::PseudoElement::Type> pseudo_element)
  1185. {
  1186. if (m_inspected_node.ptr() == node && m_inspected_pseudo_element == pseudo_element)
  1187. return;
  1188. if (auto layout_node = inspected_layout_node(); layout_node && layout_node->first_paintable())
  1189. layout_node->first_paintable()->set_needs_display();
  1190. m_inspected_node = node;
  1191. m_inspected_pseudo_element = pseudo_element;
  1192. if (auto layout_node = inspected_layout_node(); layout_node && layout_node->first_paintable())
  1193. layout_node->first_paintable()->set_needs_display();
  1194. }
  1195. Layout::Node* Document::inspected_layout_node()
  1196. {
  1197. if (!m_inspected_node)
  1198. return nullptr;
  1199. if (!m_inspected_pseudo_element.has_value() || !m_inspected_node->is_element())
  1200. return m_inspected_node->layout_node();
  1201. auto& element = static_cast<Element&>(*m_inspected_node);
  1202. return element.get_pseudo_element_node(m_inspected_pseudo_element.value());
  1203. }
  1204. static Node* find_common_ancestor(Node* a, Node* b)
  1205. {
  1206. if (!a || !b)
  1207. return nullptr;
  1208. if (a == b)
  1209. return a;
  1210. HashTable<Node*> ancestors;
  1211. for (auto* node = a; node; node = node->parent_or_shadow_host())
  1212. ancestors.set(node);
  1213. for (auto* node = b; node; node = node->parent_or_shadow_host()) {
  1214. if (ancestors.contains(node))
  1215. return node;
  1216. }
  1217. return nullptr;
  1218. }
  1219. void Document::set_hovered_node(Node* node)
  1220. {
  1221. if (m_hovered_node.ptr() == node)
  1222. return;
  1223. GC::Ptr<Node> old_hovered_node = move(m_hovered_node);
  1224. m_hovered_node = node;
  1225. auto* common_ancestor = find_common_ancestor(old_hovered_node, m_hovered_node);
  1226. if (common_ancestor)
  1227. common_ancestor->invalidate_style(StyleInvalidationReason::Hover);
  1228. else
  1229. invalidate_style(StyleInvalidationReason::Hover);
  1230. // https://w3c.github.io/uievents/#mouseout
  1231. if (old_hovered_node && old_hovered_node != m_hovered_node) {
  1232. UIEvents::MouseEventInit mouse_event_init {};
  1233. mouse_event_init.bubbles = true;
  1234. mouse_event_init.cancelable = true;
  1235. mouse_event_init.composed = true;
  1236. mouse_event_init.related_target = m_hovered_node;
  1237. auto event = UIEvents::MouseEvent::create(realm(), UIEvents::EventNames::mouseout, mouse_event_init);
  1238. old_hovered_node->dispatch_event(event);
  1239. }
  1240. // https://w3c.github.io/uievents/#mouseleave
  1241. if (old_hovered_node && (!m_hovered_node || !m_hovered_node->is_descendant_of(*old_hovered_node))) {
  1242. // FIXME: Check if we need to dispatch these events in a specific order.
  1243. for (auto target = old_hovered_node; target && target.ptr() != common_ancestor; target = target->parent()) {
  1244. // FIXME: Populate the event with mouse coordinates, etc.
  1245. UIEvents::MouseEventInit mouse_event_init {};
  1246. mouse_event_init.related_target = m_hovered_node;
  1247. target->dispatch_event(UIEvents::MouseEvent::create(realm(), UIEvents::EventNames::mouseleave, mouse_event_init));
  1248. }
  1249. }
  1250. // https://w3c.github.io/uievents/#mouseover
  1251. if (m_hovered_node && m_hovered_node != old_hovered_node) {
  1252. UIEvents::MouseEventInit mouse_event_init {};
  1253. mouse_event_init.bubbles = true;
  1254. mouse_event_init.cancelable = true;
  1255. mouse_event_init.composed = true;
  1256. mouse_event_init.related_target = old_hovered_node;
  1257. auto event = UIEvents::MouseEvent::create(realm(), UIEvents::EventNames::mouseover, mouse_event_init);
  1258. m_hovered_node->dispatch_event(event);
  1259. }
  1260. // https://w3c.github.io/uievents/#mouseenter
  1261. if (m_hovered_node && (!old_hovered_node || !m_hovered_node->is_ancestor_of(*old_hovered_node))) {
  1262. // FIXME: Check if we need to dispatch these events in a specific order.
  1263. for (auto target = m_hovered_node; target && target.ptr() != common_ancestor; target = target->parent()) {
  1264. // FIXME: Populate the event with mouse coordinates, etc.
  1265. UIEvents::MouseEventInit mouse_event_init {};
  1266. mouse_event_init.related_target = old_hovered_node;
  1267. target->dispatch_event(UIEvents::MouseEvent::create(realm(), UIEvents::EventNames::mouseenter, mouse_event_init));
  1268. }
  1269. }
  1270. }
  1271. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-getelementsbyname
  1272. GC::Ref<NodeList> Document::get_elements_by_name(FlyString const& name)
  1273. {
  1274. return LiveNodeList::create(realm(), *this, LiveNodeList::Scope::Descendants, [name](auto const& node) {
  1275. if (!is<HTML::HTMLElement>(node))
  1276. return false;
  1277. return verify_cast<HTML::HTMLElement>(node).name() == name;
  1278. });
  1279. }
  1280. // https://html.spec.whatwg.org/multipage/obsolete.html#dom-document-applets
  1281. GC::Ref<HTMLCollection> Document::applets()
  1282. {
  1283. if (!m_applets)
  1284. m_applets = HTMLCollection::create(*this, HTMLCollection::Scope::Descendants, [](auto&) { return false; });
  1285. return *m_applets;
  1286. }
  1287. // https://html.spec.whatwg.org/multipage/obsolete.html#dom-document-anchors
  1288. GC::Ref<HTMLCollection> Document::anchors()
  1289. {
  1290. if (!m_anchors) {
  1291. m_anchors = HTMLCollection::create(*this, HTMLCollection::Scope::Descendants, [](Element const& element) {
  1292. return is<HTML::HTMLAnchorElement>(element) && element.name().has_value();
  1293. });
  1294. }
  1295. return *m_anchors;
  1296. }
  1297. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-images
  1298. GC::Ref<HTMLCollection> Document::images()
  1299. {
  1300. if (!m_images) {
  1301. m_images = HTMLCollection::create(*this, HTMLCollection::Scope::Descendants, [](Element const& element) {
  1302. return is<HTML::HTMLImageElement>(element);
  1303. });
  1304. }
  1305. return *m_images;
  1306. }
  1307. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-embeds
  1308. GC::Ref<HTMLCollection> Document::embeds()
  1309. {
  1310. if (!m_embeds) {
  1311. m_embeds = HTMLCollection::create(*this, HTMLCollection::Scope::Descendants, [](Element const& element) {
  1312. return is<HTML::HTMLEmbedElement>(element);
  1313. });
  1314. }
  1315. return *m_embeds;
  1316. }
  1317. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-plugins
  1318. GC::Ref<HTMLCollection> Document::plugins()
  1319. {
  1320. return embeds();
  1321. }
  1322. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-links
  1323. GC::Ref<HTMLCollection> Document::links()
  1324. {
  1325. if (!m_links) {
  1326. m_links = HTMLCollection::create(*this, HTMLCollection::Scope::Descendants, [](Element const& element) {
  1327. return (is<HTML::HTMLAnchorElement>(element) || is<HTML::HTMLAreaElement>(element)) && element.has_attribute(HTML::AttributeNames::href);
  1328. });
  1329. }
  1330. return *m_links;
  1331. }
  1332. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-forms
  1333. GC::Ref<HTMLCollection> Document::forms()
  1334. {
  1335. if (!m_forms) {
  1336. m_forms = HTMLCollection::create(*this, HTMLCollection::Scope::Descendants, [](Element const& element) {
  1337. return is<HTML::HTMLFormElement>(element);
  1338. });
  1339. }
  1340. return *m_forms;
  1341. }
  1342. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-scripts
  1343. GC::Ref<HTMLCollection> Document::scripts()
  1344. {
  1345. if (!m_scripts) {
  1346. m_scripts = HTMLCollection::create(*this, HTMLCollection::Scope::Descendants, [](Element const& element) {
  1347. return is<HTML::HTMLScriptElement>(element);
  1348. });
  1349. }
  1350. return *m_scripts;
  1351. }
  1352. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-all
  1353. GC::Ref<HTML::HTMLAllCollection> Document::all()
  1354. {
  1355. if (!m_all) {
  1356. // The all attribute must return an HTMLAllCollection rooted at the Document node, whose filter matches all elements.
  1357. m_all = HTML::HTMLAllCollection::create(*this, HTML::HTMLAllCollection::Scope::Descendants, [](Element const&) {
  1358. return true;
  1359. });
  1360. }
  1361. return *m_all;
  1362. }
  1363. // https://drafts.csswg.org/css-font-loading/#font-source
  1364. GC::Ref<CSS::FontFaceSet> Document::fonts()
  1365. {
  1366. if (!m_fonts)
  1367. m_fonts = CSS::FontFaceSet::create(realm());
  1368. return *m_fonts;
  1369. }
  1370. // https://html.spec.whatwg.org/multipage/obsolete.html#dom-document-clear
  1371. void Document::clear()
  1372. {
  1373. // Do nothing
  1374. }
  1375. // https://html.spec.whatwg.org/multipage/obsolete.html#dom-document-captureevents
  1376. void Document::capture_events()
  1377. {
  1378. // Do nothing
  1379. }
  1380. // https://html.spec.whatwg.org/multipage/obsolete.html#dom-document-releaseevents
  1381. void Document::release_events()
  1382. {
  1383. // Do nothing
  1384. }
  1385. Color Document::normal_link_color() const
  1386. {
  1387. if (m_normal_link_color.has_value())
  1388. return m_normal_link_color.value();
  1389. return CSS::SystemColor::link_text();
  1390. }
  1391. Color Document::active_link_color() const
  1392. {
  1393. if (m_active_link_color.has_value())
  1394. return m_active_link_color.value();
  1395. return CSS::SystemColor::active_text();
  1396. }
  1397. Color Document::visited_link_color() const
  1398. {
  1399. if (m_visited_link_color.has_value())
  1400. return m_visited_link_color.value();
  1401. return CSS::SystemColor::visited_text();
  1402. }
  1403. // https://html.spec.whatwg.org/multipage/webappapis.html#relevant-settings-object
  1404. HTML::EnvironmentSettingsObject& Document::relevant_settings_object() const
  1405. {
  1406. // Then, the relevant settings object for a platform object o is the environment settings object of the relevant Realm for o.
  1407. return Bindings::principal_host_defined_environment_settings_object(realm());
  1408. }
  1409. // https://dom.spec.whatwg.org/#dom-document-createelement
  1410. WebIDL::ExceptionOr<GC::Ref<Element>> Document::create_element(String const& a_local_name, Variant<String, ElementCreationOptions> const& options)
  1411. {
  1412. auto local_name = a_local_name.to_byte_string();
  1413. // 1. If localName does not match the Name production, then throw an "InvalidCharacterError" DOMException.
  1414. if (!is_valid_name(a_local_name))
  1415. return WebIDL::InvalidCharacterError::create(realm(), "Invalid character in tag name."_string);
  1416. // 2. If this is an HTML document, then set localName to localName in ASCII lowercase.
  1417. if (document_type() == Type::HTML)
  1418. local_name = local_name.to_lowercase();
  1419. // 3. Let is be null.
  1420. Optional<String> is_value;
  1421. // 4. If options is a dictionary and options["is"] exists, then set is to it.
  1422. if (options.has<ElementCreationOptions>()) {
  1423. auto const& element_creation_options = options.get<ElementCreationOptions>();
  1424. if (element_creation_options.is.has_value())
  1425. is_value = element_creation_options.is.value();
  1426. }
  1427. // 5. Let namespace be the HTML namespace, if this is an HTML document or this’s content type is "application/xhtml+xml"; otherwise null.
  1428. Optional<FlyString> namespace_;
  1429. if (document_type() == Type::HTML || content_type() == "application/xhtml+xml"sv)
  1430. namespace_ = Namespace::HTML;
  1431. // 6. Return the result of creating an element given this, localName, namespace, null, is, and with the synchronous custom elements flag set.
  1432. return TRY(DOM::create_element(*this, MUST(FlyString::from_deprecated_fly_string(local_name)), move(namespace_), {}, move(is_value), true));
  1433. }
  1434. // https://dom.spec.whatwg.org/#dom-document-createelementns
  1435. // https://dom.spec.whatwg.org/#internal-createelementns-steps
  1436. WebIDL::ExceptionOr<GC::Ref<Element>> Document::create_element_ns(Optional<FlyString> const& namespace_, String const& qualified_name, Variant<String, ElementCreationOptions> const& options)
  1437. {
  1438. // 1. Let namespace, prefix, and localName be the result of passing namespace and qualifiedName to validate and extract.
  1439. auto extracted_qualified_name = TRY(validate_and_extract(realm(), namespace_, qualified_name));
  1440. // 2. Let is be null.
  1441. Optional<String> is_value;
  1442. // 3. If options is a dictionary and options["is"] exists, then set is to it.
  1443. if (options.has<ElementCreationOptions>()) {
  1444. auto const& element_creation_options = options.get<ElementCreationOptions>();
  1445. if (element_creation_options.is.has_value())
  1446. is_value = element_creation_options.is.value();
  1447. }
  1448. // 4. Return the result of creating an element given document, localName, namespace, prefix, is, and with the synchronous custom elements flag set.
  1449. return TRY(DOM::create_element(*this, extracted_qualified_name.local_name(), extracted_qualified_name.namespace_(), extracted_qualified_name.prefix(), move(is_value), true));
  1450. }
  1451. GC::Ref<DocumentFragment> Document::create_document_fragment()
  1452. {
  1453. return realm().create<DocumentFragment>(*this);
  1454. }
  1455. GC::Ref<Text> Document::create_text_node(String const& data)
  1456. {
  1457. return realm().create<Text>(*this, data);
  1458. }
  1459. // https://dom.spec.whatwg.org/#dom-document-createcdatasection
  1460. WebIDL::ExceptionOr<GC::Ref<CDATASection>> Document::create_cdata_section(String const& data)
  1461. {
  1462. // 1. If this is an HTML document, then throw a "NotSupportedError" DOMException.
  1463. if (is_html_document())
  1464. return WebIDL::NotSupportedError::create(realm(), "This operation is not supported for HTML documents"_string);
  1465. // 2. If data contains the string "]]>", then throw an "InvalidCharacterError" DOMException.
  1466. if (data.contains("]]>"sv))
  1467. return WebIDL::InvalidCharacterError::create(realm(), "String may not contain ']]>'"_string);
  1468. // 3. Return a new CDATASection node with its data set to data and node document set to this.
  1469. return realm().create<CDATASection>(*this, data);
  1470. }
  1471. GC::Ref<Comment> Document::create_comment(String const& data)
  1472. {
  1473. return realm().create<Comment>(*this, data);
  1474. }
  1475. // https://dom.spec.whatwg.org/#dom-document-createprocessinginstruction
  1476. WebIDL::ExceptionOr<GC::Ref<ProcessingInstruction>> Document::create_processing_instruction(String const& target, String const& data)
  1477. {
  1478. // 1. If target does not match the Name production, then throw an "InvalidCharacterError" DOMException.
  1479. if (!is_valid_name(target))
  1480. return WebIDL::InvalidCharacterError::create(realm(), "Invalid character in target name."_string);
  1481. // 2. If data contains the string "?>", then throw an "InvalidCharacterError" DOMException.
  1482. if (data.contains("?>"sv))
  1483. return WebIDL::InvalidCharacterError::create(realm(), "String may not contain '?>'"_string);
  1484. // 3. Return a new ProcessingInstruction node, with target set to target, data set to data, and node document set to this.
  1485. return realm().create<ProcessingInstruction>(*this, data, target);
  1486. }
  1487. GC::Ref<Range> Document::create_range()
  1488. {
  1489. return Range::create(*this);
  1490. }
  1491. // https://dom.spec.whatwg.org/#dom-document-createevent
  1492. WebIDL::ExceptionOr<GC::Ref<Event>> Document::create_event(StringView interface)
  1493. {
  1494. auto& realm = this->realm();
  1495. // NOTE: This is named event here, since we do step 5 and 6 as soon as possible for each case.
  1496. // 1. Let constructor be null.
  1497. GC::Ptr<Event> event;
  1498. // 2. If interface is an ASCII case-insensitive match for any of the strings in the first column in the following table,
  1499. // then set constructor to the interface in the second column on the same row as the matching string:
  1500. if (Infra::is_ascii_case_insensitive_match(interface, "beforeunloadevent"sv)) {
  1501. event = HTML::BeforeUnloadEvent::create(realm, FlyString {});
  1502. } else if (Infra::is_ascii_case_insensitive_match(interface, "compositionevent"sv)) {
  1503. event = UIEvents::CompositionEvent::create(realm, String {});
  1504. } else if (Infra::is_ascii_case_insensitive_match(interface, "customevent"sv)) {
  1505. event = CustomEvent::create(realm, FlyString {});
  1506. } else if (Infra::is_ascii_case_insensitive_match(interface, "devicemotionevent"sv)) {
  1507. event = Event::create(realm, FlyString {}); // FIXME: Create DeviceMotionEvent
  1508. } else if (Infra::is_ascii_case_insensitive_match(interface, "deviceorientationevent"sv)) {
  1509. event = Event::create(realm, FlyString {}); // FIXME: Create DeviceOrientationEvent
  1510. } else if (Infra::is_ascii_case_insensitive_match(interface, "dragevent"sv)) {
  1511. event = Event::create(realm, FlyString {}); // FIXME: Create DragEvent
  1512. } else if (Infra::is_ascii_case_insensitive_match(interface, "event"sv)
  1513. || Infra::is_ascii_case_insensitive_match(interface, "events"sv)) {
  1514. event = Event::create(realm, FlyString {});
  1515. } else if (Infra::is_ascii_case_insensitive_match(interface, "focusevent"sv)) {
  1516. event = UIEvents::FocusEvent::create(realm, FlyString {});
  1517. } else if (Infra::is_ascii_case_insensitive_match(interface, "hashchangeevent"sv)) {
  1518. event = HTML::HashChangeEvent::create(realm, FlyString {}, {});
  1519. } else if (Infra::is_ascii_case_insensitive_match(interface, "htmlevents"sv)) {
  1520. event = Event::create(realm, FlyString {});
  1521. } else if (Infra::is_ascii_case_insensitive_match(interface, "keyboardevent"sv)) {
  1522. event = UIEvents::KeyboardEvent::create(realm, String {});
  1523. } else if (Infra::is_ascii_case_insensitive_match(interface, "messageevent"sv)) {
  1524. event = HTML::MessageEvent::create(realm, String {});
  1525. } else if (Infra::is_ascii_case_insensitive_match(interface, "mouseevent"sv)
  1526. || Infra::is_ascii_case_insensitive_match(interface, "mouseevents"sv)) {
  1527. event = UIEvents::MouseEvent::create(realm, FlyString {});
  1528. } else if (Infra::is_ascii_case_insensitive_match(interface, "storageevent"sv)) {
  1529. event = Event::create(realm, FlyString {}); // FIXME: Create StorageEvent
  1530. } else if (Infra::is_ascii_case_insensitive_match(interface, "svgevents"sv)) {
  1531. event = Event::create(realm, FlyString {});
  1532. } else if (Infra::is_ascii_case_insensitive_match(interface, "textevent"sv)) {
  1533. event = UIEvents::TextEvent::create(realm, FlyString {});
  1534. } else if (Infra::is_ascii_case_insensitive_match(interface, "touchevent"sv)) {
  1535. event = Event::create(realm, FlyString {}); // FIXME: Create TouchEvent
  1536. } else if (Infra::is_ascii_case_insensitive_match(interface, "uievent"sv)
  1537. || Infra::is_ascii_case_insensitive_match(interface, "uievents"sv)) {
  1538. event = UIEvents::UIEvent::create(realm, FlyString {});
  1539. }
  1540. // 3. If constructor is null, then throw a "NotSupportedError" DOMException.
  1541. if (!event) {
  1542. return WebIDL::NotSupportedError::create(realm, "No constructor for interface found"_string);
  1543. }
  1544. // FIXME: 4. If the interface indicated by constructor is not exposed on the relevant global object of this, then throw a "NotSupportedError" DOMException.
  1545. // NOTE: These are done in the if-chain above
  1546. // 5. Let event be the result of creating an event given constructor.
  1547. // 6. Initialize event’s type attribute to the empty string.
  1548. // 7. Initialize event’s timeStamp attribute to the result of calling current high resolution time with this’s relevant global object.
  1549. // NOTE: This is handled by each constructor.
  1550. // 8. Initialize event’s isTrusted attribute to false.
  1551. event->set_is_trusted(false);
  1552. // 9. Unset event’s initialized flag.
  1553. event->set_initialized(false);
  1554. // 10. Return event.
  1555. return GC::Ref(*event);
  1556. }
  1557. void Document::set_pending_parsing_blocking_script(HTML::HTMLScriptElement* script)
  1558. {
  1559. m_pending_parsing_blocking_script = script;
  1560. }
  1561. GC::Ref<HTML::HTMLScriptElement> Document::take_pending_parsing_blocking_script(Badge<HTML::HTMLParser>)
  1562. {
  1563. VERIFY(m_pending_parsing_blocking_script);
  1564. auto script = m_pending_parsing_blocking_script;
  1565. m_pending_parsing_blocking_script = nullptr;
  1566. return *script;
  1567. }
  1568. void Document::add_script_to_execute_when_parsing_has_finished(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement& script)
  1569. {
  1570. m_scripts_to_execute_when_parsing_has_finished.append(script);
  1571. }
  1572. Vector<GC::Root<HTML::HTMLScriptElement>> Document::take_scripts_to_execute_when_parsing_has_finished(Badge<HTML::HTMLParser>)
  1573. {
  1574. Vector<GC::Root<HTML::HTMLScriptElement>> handles;
  1575. for (auto script : m_scripts_to_execute_when_parsing_has_finished)
  1576. handles.append(GC::make_root(script));
  1577. m_scripts_to_execute_when_parsing_has_finished.clear();
  1578. return handles;
  1579. }
  1580. void Document::add_script_to_execute_as_soon_as_possible(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement& script)
  1581. {
  1582. m_scripts_to_execute_as_soon_as_possible.append(script);
  1583. }
  1584. Vector<GC::Root<HTML::HTMLScriptElement>> Document::take_scripts_to_execute_as_soon_as_possible(Badge<HTML::HTMLParser>)
  1585. {
  1586. Vector<GC::Root<HTML::HTMLScriptElement>> handles;
  1587. for (auto script : m_scripts_to_execute_as_soon_as_possible)
  1588. handles.append(GC::make_root(script));
  1589. m_scripts_to_execute_as_soon_as_possible.clear();
  1590. return handles;
  1591. }
  1592. void Document::add_script_to_execute_in_order_as_soon_as_possible(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement& script)
  1593. {
  1594. m_scripts_to_execute_in_order_as_soon_as_possible.append(script);
  1595. }
  1596. Vector<GC::Root<HTML::HTMLScriptElement>> Document::take_scripts_to_execute_in_order_as_soon_as_possible(Badge<HTML::HTMLParser>)
  1597. {
  1598. Vector<GC::Root<HTML::HTMLScriptElement>> handles;
  1599. for (auto script : m_scripts_to_execute_in_order_as_soon_as_possible)
  1600. handles.append(GC::make_root(script));
  1601. m_scripts_to_execute_in_order_as_soon_as_possible.clear();
  1602. return handles;
  1603. }
  1604. // https://dom.spec.whatwg.org/#dom-document-importnode
  1605. WebIDL::ExceptionOr<GC::Ref<Node>> Document::import_node(GC::Ref<Node> node, bool deep)
  1606. {
  1607. // 1. If node is a document or shadow root, then throw a "NotSupportedError" DOMException.
  1608. if (is<Document>(*node) || is<ShadowRoot>(*node))
  1609. return WebIDL::NotSupportedError::create(realm(), "Cannot import a document or shadow root."_string);
  1610. // 2. Return a clone of node, with this and the clone children flag set if deep is true.
  1611. return node->clone_node(this, deep);
  1612. }
  1613. // https://dom.spec.whatwg.org/#concept-node-adopt
  1614. void Document::adopt_node(Node& node)
  1615. {
  1616. // 1. Let oldDocument be node’s node document.
  1617. auto& old_document = node.document();
  1618. // 2. If node’s parent is non-null, then remove node.
  1619. if (node.parent())
  1620. node.remove();
  1621. // 3. If document is not oldDocument, then:
  1622. if (&old_document != this) {
  1623. // 1. For each inclusiveDescendant in node’s shadow-including inclusive descendants:
  1624. node.for_each_shadow_including_inclusive_descendant([&](DOM::Node& inclusive_descendant) {
  1625. // 1. Set inclusiveDescendant’s node document to document.
  1626. inclusive_descendant.set_document({}, *this);
  1627. // FIXME: 2. If inclusiveDescendant is an element, then set the node document of each attribute in inclusiveDescendant’s
  1628. // attribute list to document.
  1629. return TraversalDecision::Continue;
  1630. });
  1631. // 2. For each inclusiveDescendant in node’s shadow-including inclusive descendants that is custom,
  1632. // enqueue a custom element callback reaction with inclusiveDescendant, callback name "adoptedCallback",
  1633. // and an argument list containing oldDocument and document.
  1634. node.for_each_shadow_including_inclusive_descendant([&](DOM::Node& inclusive_descendant) {
  1635. if (!is<DOM::Element>(inclusive_descendant))
  1636. return TraversalDecision::Continue;
  1637. auto& element = static_cast<DOM::Element&>(inclusive_descendant);
  1638. if (element.is_custom()) {
  1639. auto& vm = this->vm();
  1640. GC::RootVector<JS::Value> arguments { vm.heap() };
  1641. arguments.append(&old_document);
  1642. arguments.append(this);
  1643. element.enqueue_a_custom_element_callback_reaction(HTML::CustomElementReactionNames::adoptedCallback, move(arguments));
  1644. }
  1645. return TraversalDecision::Continue;
  1646. });
  1647. // 3. For each inclusiveDescendant in node’s shadow-including inclusive descendants, in shadow-including tree order,
  1648. // run the adopting steps with inclusiveDescendant and oldDocument.
  1649. node.for_each_shadow_including_inclusive_descendant([&](auto& inclusive_descendant) {
  1650. inclusive_descendant.adopted_from(old_document);
  1651. return TraversalDecision::Continue;
  1652. });
  1653. // Transfer NodeIterators rooted at `node` from old_document to this document.
  1654. Vector<NodeIterator&> node_iterators_to_transfer;
  1655. for (auto node_iterator : old_document.m_node_iterators) {
  1656. if (node_iterator->root().ptr() == &node)
  1657. node_iterators_to_transfer.append(*node_iterator);
  1658. }
  1659. for (auto& node_iterator : node_iterators_to_transfer) {
  1660. old_document.m_node_iterators.remove(&node_iterator);
  1661. m_node_iterators.set(&node_iterator);
  1662. }
  1663. }
  1664. }
  1665. // https://dom.spec.whatwg.org/#dom-document-adoptnode
  1666. WebIDL::ExceptionOr<GC::Ref<Node>> Document::adopt_node_binding(GC::Ref<Node> node)
  1667. {
  1668. if (is<Document>(*node))
  1669. return WebIDL::NotSupportedError::create(realm(), "Cannot adopt a document into a document"_string);
  1670. if (is<ShadowRoot>(*node))
  1671. return WebIDL::HierarchyRequestError::create(realm(), "Cannot adopt a shadow root into a document"_string);
  1672. if (is<DocumentFragment>(*node) && verify_cast<DocumentFragment>(*node).host())
  1673. return node;
  1674. adopt_node(*node);
  1675. return node;
  1676. }
  1677. DocumentType const* Document::doctype() const
  1678. {
  1679. return first_child_of_type<DocumentType>();
  1680. }
  1681. String const& Document::compat_mode() const
  1682. {
  1683. static String const back_compat = "BackCompat"_string;
  1684. static String const css1_compat = "CSS1Compat"_string;
  1685. if (m_quirks_mode == QuirksMode::Yes)
  1686. return back_compat;
  1687. return css1_compat;
  1688. }
  1689. // https://html.spec.whatwg.org/multipage/interaction.html#dom-documentorshadowroot-activeelement
  1690. void Document::update_active_element()
  1691. {
  1692. // 1. Let candidate be the DOM anchor of the focused area of this DocumentOrShadowRoot's node document.
  1693. Node* candidate = focused_element();
  1694. // 2. Set candidate to the result of retargeting candidate against this DocumentOrShadowRoot.
  1695. candidate = verify_cast<Node>(retarget(candidate, this));
  1696. // 3. If candidate's root is not this DocumentOrShadowRoot, then return null.
  1697. if (&candidate->root() != this) {
  1698. set_active_element(nullptr);
  1699. return;
  1700. }
  1701. // 4. If candidate is not a Document object, then return candidate.
  1702. if (!is<Document>(candidate)) {
  1703. set_active_element(verify_cast<Element>(candidate));
  1704. return;
  1705. }
  1706. auto* candidate_document = static_cast<Document*>(candidate);
  1707. // 5. If candidate has a body element, then return that body element.
  1708. if (candidate_document->body()) {
  1709. set_active_element(candidate_document->body());
  1710. return;
  1711. }
  1712. // 6. If candidate's document element is non-null, then return that document element.
  1713. if (candidate_document->document_element()) {
  1714. set_active_element(candidate_document->document_element());
  1715. return;
  1716. }
  1717. // 7. Return null.
  1718. set_active_element(nullptr);
  1719. return;
  1720. }
  1721. void Document::set_focused_element(Element* element)
  1722. {
  1723. if (m_focused_element.ptr() == element)
  1724. return;
  1725. GC::Ptr<Element> old_focused_element = move(m_focused_element);
  1726. if (old_focused_element)
  1727. old_focused_element->did_lose_focus();
  1728. m_focused_element = element;
  1729. if (auto* invalidation_target = find_common_ancestor(old_focused_element, m_focused_element) ?: this)
  1730. invalidation_target->invalidate_style(StyleInvalidationReason::FocusedElementChange);
  1731. if (m_focused_element)
  1732. m_focused_element->did_receive_focus();
  1733. if (paintable())
  1734. paintable()->set_needs_display();
  1735. // Scroll the viewport if necessary to make the newly focused element visible.
  1736. if (m_focused_element) {
  1737. m_focused_element->queue_an_element_task(HTML::Task::Source::UserInteraction, [&]() {
  1738. ScrollIntoViewOptions scroll_options;
  1739. scroll_options.block = Bindings::ScrollLogicalPosition::Nearest;
  1740. scroll_options.inline_ = Bindings::ScrollLogicalPosition::Nearest;
  1741. (void)m_focused_element->scroll_into_view(scroll_options);
  1742. });
  1743. }
  1744. update_active_element();
  1745. }
  1746. void Document::set_active_element(Element* element)
  1747. {
  1748. if (m_active_element.ptr() == element)
  1749. return;
  1750. GC::Ptr<Node> old_active_element = move(m_active_element);
  1751. m_active_element = element;
  1752. if (auto* invalidation_target = find_common_ancestor(old_active_element, m_active_element) ?: this)
  1753. invalidation_target->invalidate_style(StyleInvalidationReason::TargetElementChange);
  1754. if (paintable())
  1755. paintable()->set_needs_display();
  1756. }
  1757. void Document::set_target_element(Element* element)
  1758. {
  1759. if (m_target_element.ptr() == element)
  1760. return;
  1761. GC::Ptr<Element> old_target_element = move(m_target_element);
  1762. m_target_element = element;
  1763. if (auto* invalidation_target = find_common_ancestor(old_target_element, m_target_element) ?: this)
  1764. invalidation_target->invalidate_style(StyleInvalidationReason::TargetElementChange);
  1765. if (paintable())
  1766. paintable()->set_needs_display();
  1767. }
  1768. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#the-indicated-part-of-the-document
  1769. Document::IndicatedPart Document::determine_the_indicated_part() const
  1770. {
  1771. // For an HTML document document, the following processing model must be followed to determine its indicated part:
  1772. // 1. Let fragment be document's URL's fragment.
  1773. auto fragment = url().fragment();
  1774. // 2. If fragment is the empty string, then return the special value top of the document.
  1775. if (!fragment.has_value() || fragment->is_empty())
  1776. return Document::TopOfTheDocument {};
  1777. // 3. Let potentialIndicatedElement be the result of finding a potential indicated element given document and fragment.
  1778. auto* potential_indicated_element = find_a_potential_indicated_element(*fragment);
  1779. // 4. If potentialIndicatedElement is not null, then return potentialIndicatedElement.
  1780. if (potential_indicated_element)
  1781. return potential_indicated_element;
  1782. // 5. Let fragmentBytes be the result of percent-decoding fragment.
  1783. // 6. Let decodedFragment be the result of running UTF-8 decode without BOM on fragmentBytes.
  1784. auto decoded_fragment = URL::percent_decode(*fragment);
  1785. // 7. Set potentialIndicatedElement to the result of finding a potential indicated element given document and decodedFragment.
  1786. potential_indicated_element = find_a_potential_indicated_element(MUST(FlyString::from_deprecated_fly_string(decoded_fragment)));
  1787. // 8. If potentialIndicatedElement is not null, then return potentialIndicatedElement.
  1788. if (potential_indicated_element)
  1789. return potential_indicated_element;
  1790. // 9. If decodedFragment is an ASCII case-insensitive match for the string top, then return the top of the document.
  1791. if (Infra::is_ascii_case_insensitive_match(decoded_fragment, "top"sv))
  1792. return Document::TopOfTheDocument {};
  1793. // 10. Return null.
  1794. return nullptr;
  1795. }
  1796. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#find-a-potential-indicated-element
  1797. Element* Document::find_a_potential_indicated_element(FlyString const& fragment) const
  1798. {
  1799. // To find a potential indicated element given a Document document and a string fragment, run these steps:
  1800. // 1. If there is an element in the document tree whose root is document and that has an ID equal to
  1801. // fragment, then return the first such element in tree order.
  1802. if (auto element = get_element_by_id(fragment))
  1803. return const_cast<Element*>(element.ptr());
  1804. // 2. If there is an a element in the document tree whose root is document that has a name attribute
  1805. // whose value is equal to fragment, then return the first such element in tree order.
  1806. Element* element_with_name = nullptr;
  1807. root().for_each_in_subtree_of_type<Element>([&](Element const& element) {
  1808. if (element.name() == fragment) {
  1809. element_with_name = const_cast<Element*>(&element);
  1810. return TraversalDecision::Break;
  1811. }
  1812. return TraversalDecision::Continue;
  1813. });
  1814. if (element_with_name)
  1815. return element_with_name;
  1816. // 3. Return null.
  1817. return nullptr;
  1818. }
  1819. // https://drafts.csswg.org/css-transitions-2/#event-dispatch
  1820. void Document::dispatch_events_for_transition(GC::Ref<CSS::CSSTransition> transition)
  1821. {
  1822. auto previous_phase = transition->previous_phase();
  1823. using Phase = CSS::CSSTransition::Phase;
  1824. // The transition phase of a transition is initially ‘idle’ and is updated on each
  1825. // animation frame according to the first matching condition from below:
  1826. auto transition_phase = Phase::Idle;
  1827. if (!transition->effect()) {
  1828. // If the transition has no associated effect,
  1829. if (!transition->current_time().has_value()) {
  1830. // If the transition has an unresolved current time,
  1831. // The transition phase is ‘idle’.
  1832. } else if (transition->current_time().value() < 0.0) {
  1833. // If the transition has a current time < 0,
  1834. // The transition phase is ‘before’.
  1835. transition_phase = Phase::Before;
  1836. } else {
  1837. // Otherwise,
  1838. // The transition phase is ‘after’.
  1839. transition_phase = Phase::After;
  1840. }
  1841. } else if (transition->pending() && (previous_phase == Phase::Idle || previous_phase == Phase::Pending)) {
  1842. // If the transition has a pending play task or a pending pause task
  1843. // and its phase was previously ‘idle’ or ‘pending’,
  1844. // The transition phase is ‘pending’.
  1845. transition_phase = Phase::Pending;
  1846. } else {
  1847. // Otherwise,
  1848. // The transition phase is the phase of its associated effect.
  1849. transition_phase = Phase(to_underlying(transition->effect()->phase()));
  1850. }
  1851. enum class Interval : u8 {
  1852. Start,
  1853. End,
  1854. ActiveTime,
  1855. };
  1856. auto dispatch_event = [&](FlyString const& type, Interval interval) {
  1857. // The target for a transition event is the transition’s owning element. If there is no owning element,
  1858. // no transition events are dispatched.
  1859. if (!transition->effect() || !transition->owning_element())
  1860. return;
  1861. auto effect = transition->effect();
  1862. double elapsed_time = [&]() {
  1863. if (interval == Interval::Start)
  1864. return max(min(-effect->start_delay(), effect->active_duration()), 0) / 1000;
  1865. if (interval == Interval::End)
  1866. return max(min(transition->associated_effect_end() - effect->start_delay(), effect->active_duration()), 0) / 1000;
  1867. if (interval == Interval::ActiveTime) {
  1868. // The active time of the animation at the moment it was canceled calculated using a fill mode of both.
  1869. // FIXME: Compute this properly.
  1870. return 0.0;
  1871. }
  1872. VERIFY_NOT_REACHED();
  1873. }();
  1874. append_pending_animation_event({
  1875. .event = CSS::TransitionEvent::create(
  1876. transition->owning_element()->realm(),
  1877. type,
  1878. CSS::TransitionEventInit {
  1879. { .bubbles = true },
  1880. // FIXME: Correctly set property_name and pseudo_element
  1881. String {},
  1882. elapsed_time,
  1883. String {},
  1884. }),
  1885. .animation = transition,
  1886. .target = *transition->owning_element(),
  1887. .scheduled_event_time = HighResolutionTime::unsafe_shared_current_time(),
  1888. });
  1889. };
  1890. if (previous_phase == Phase::Idle) {
  1891. if (transition_phase == Phase::Pending || transition_phase == Phase::Before)
  1892. dispatch_event(HTML::EventNames::transitionrun, Interval::Start);
  1893. if (transition_phase == Phase::Active) {
  1894. dispatch_event(HTML::EventNames::transitionrun, Interval::Start);
  1895. dispatch_event(HTML::EventNames::transitionstart, Interval::Start);
  1896. }
  1897. if (transition_phase == Phase::After) {
  1898. dispatch_event(HTML::EventNames::transitionrun, Interval::Start);
  1899. dispatch_event(HTML::EventNames::transitionstart, Interval::Start);
  1900. dispatch_event(HTML::EventNames::transitionend, Interval::End);
  1901. }
  1902. } else if (previous_phase == Phase::Pending || previous_phase == Phase::Before) {
  1903. if (transition_phase == Phase::Active)
  1904. dispatch_event(HTML::EventNames::transitionstart, Interval::Start);
  1905. if (transition_phase == Phase::After) {
  1906. dispatch_event(HTML::EventNames::transitionstart, Interval::Start);
  1907. dispatch_event(HTML::EventNames::transitionend, Interval::End);
  1908. }
  1909. } else if (previous_phase == Phase::Active) {
  1910. if (transition_phase == Phase::After)
  1911. dispatch_event(HTML::EventNames::transitionend, Interval::End);
  1912. if (transition_phase == Phase::Before)
  1913. dispatch_event(HTML::EventNames::transitionend, Interval::Start);
  1914. } else if (previous_phase == Phase::After) {
  1915. if (transition_phase == Phase::Active)
  1916. dispatch_event(HTML::EventNames::transitionstart, Interval::End);
  1917. if (transition_phase == Phase::Before) {
  1918. dispatch_event(HTML::EventNames::transitionstart, Interval::End);
  1919. dispatch_event(HTML::EventNames::transitionend, Interval::Start);
  1920. }
  1921. }
  1922. if (transition_phase == Phase::Idle) {
  1923. if (previous_phase != Phase::Idle && previous_phase != Phase::After)
  1924. dispatch_event(HTML::EventNames::animationstart, Interval::ActiveTime);
  1925. }
  1926. transition->set_previous_phase(transition_phase);
  1927. }
  1928. // https://www.w3.org/TR/css-animations-2/#event-dispatch
  1929. void Document::dispatch_events_for_animation_if_necessary(GC::Ref<Animations::Animation> animation)
  1930. {
  1931. if (animation->is_css_transition()) {
  1932. dispatch_events_for_transition(verify_cast<CSS::CSSTransition>(*animation));
  1933. return;
  1934. }
  1935. // Each time a new animation frame is established and the animation does not have a pending play task or pending
  1936. // pause task, the events to dispatch are determined by comparing the animation’s phase before and after
  1937. // establishing the new animation frame as follows:
  1938. auto effect = animation->effect();
  1939. if (!effect || !effect->is_keyframe_effect() || !animation->is_css_animation() || animation->pending())
  1940. return;
  1941. auto& css_animation = verify_cast<CSS::CSSAnimation>(*animation);
  1942. GC::Ptr<Element> target = effect->target();
  1943. if (!target)
  1944. return;
  1945. if (target->paintable())
  1946. target->paintable()->set_needs_display();
  1947. auto previous_phase = effect->previous_phase();
  1948. auto current_phase = effect->phase();
  1949. auto current_iteration = effect->current_iteration().value_or(0.0);
  1950. auto owning_element = css_animation.owning_element();
  1951. auto dispatch_event = [&](FlyString const& name, double elapsed_time) {
  1952. append_pending_animation_event({
  1953. .event = CSS::AnimationEvent::create(
  1954. owning_element->realm(),
  1955. name,
  1956. {
  1957. { .bubbles = true },
  1958. css_animation.id(),
  1959. elapsed_time,
  1960. }),
  1961. .animation = css_animation,
  1962. .target = *target,
  1963. .scheduled_event_time = HighResolutionTime::unsafe_shared_current_time(),
  1964. });
  1965. };
  1966. // For calculating the elapsedTime of each event, the following definitions are used:
  1967. // - interval start = max(min(-start delay, active duration), 0)
  1968. auto interval_start = max(min(-effect->start_delay(), effect->active_duration()), 0.0);
  1969. // - interval end = max(min(associated effect end - start delay, active duration), 0)
  1970. auto interval_end = max(min(effect->end_time() - effect->start_delay(), effect->active_duration()), 0.0);
  1971. switch (previous_phase) {
  1972. case Animations::AnimationEffect::Phase::Before:
  1973. [[fallthrough]];
  1974. case Animations::AnimationEffect::Phase::Idle:
  1975. if (current_phase == Animations::AnimationEffect::Phase::Active) {
  1976. dispatch_event(HTML::EventNames::animationstart, interval_start);
  1977. } else if (current_phase == Animations::AnimationEffect::Phase::After) {
  1978. dispatch_event(HTML::EventNames::animationstart, interval_start);
  1979. dispatch_event(HTML::EventNames::animationend, interval_end);
  1980. }
  1981. break;
  1982. case Animations::AnimationEffect::Phase::Active:
  1983. if (current_phase == Animations::AnimationEffect::Phase::Before) {
  1984. dispatch_event(HTML::EventNames::animationend, interval_start);
  1985. } else if (current_phase == Animations::AnimationEffect::Phase::Active) {
  1986. auto previous_current_iteration = effect->previous_current_iteration();
  1987. if (previous_current_iteration != current_iteration) {
  1988. // The elapsed time for an animationiteration event is defined as follows:
  1989. // 1. Let previous current iteration be the current iteration from the previous animation frame.
  1990. // 2. If previous current iteration is greater than current iteration, let iteration boundary be current iteration + 1,
  1991. // otherwise let it be current iteration.
  1992. auto iteration_boundary = previous_current_iteration > current_iteration ? current_iteration + 1 : current_iteration;
  1993. // 3. The elapsed time is the result of evaluating (iteration boundary - iteration start) × iteration duration).
  1994. auto iteration_duration_variant = effect->iteration_duration();
  1995. auto iteration_duration = iteration_duration_variant.has<String>() ? 0.0 : iteration_duration_variant.get<double>();
  1996. auto elapsed_time = (iteration_boundary - effect->iteration_start()) * iteration_duration;
  1997. dispatch_event(HTML::EventNames::animationiteration, elapsed_time);
  1998. }
  1999. } else if (current_phase == Animations::AnimationEffect::Phase::After) {
  2000. dispatch_event(HTML::EventNames::animationend, interval_end);
  2001. }
  2002. break;
  2003. case Animations::AnimationEffect::Phase::After:
  2004. if (current_phase == Animations::AnimationEffect::Phase::Active) {
  2005. dispatch_event(HTML::EventNames::animationstart, interval_end);
  2006. } else if (current_phase == Animations::AnimationEffect::Phase::Before) {
  2007. dispatch_event(HTML::EventNames::animationstart, interval_end);
  2008. dispatch_event(HTML::EventNames::animationend, interval_start);
  2009. }
  2010. break;
  2011. }
  2012. if (current_phase == Animations::AnimationEffect::Phase::Idle && previous_phase != Animations::AnimationEffect::Phase::Idle && previous_phase != Animations::AnimationEffect::Phase::After) {
  2013. // FIXME: Calculate a non-zero time when the animation is cancelled by means other than calling cancel()
  2014. auto cancel_time = animation->release_saved_cancel_time().value_or(0.0);
  2015. dispatch_event(HTML::EventNames::animationcancel, cancel_time);
  2016. }
  2017. effect->set_previous_phase(current_phase);
  2018. effect->set_previous_current_iteration(current_iteration);
  2019. }
  2020. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#scroll-to-the-fragment-identifier
  2021. void Document::scroll_to_the_fragment()
  2022. {
  2023. // To scroll to the fragment given a Document document:
  2024. // 1. If document's indicated part is null, then set document's target element to null.
  2025. auto indicated_part = determine_the_indicated_part();
  2026. if (indicated_part.has<Element*>() && indicated_part.get<Element*>() == nullptr) {
  2027. set_target_element(nullptr);
  2028. }
  2029. // 2. Otherwise, if document's indicated part is top of the document, then:
  2030. else if (indicated_part.has<TopOfTheDocument>()) {
  2031. // 1. Set document's target element to null.
  2032. set_target_element(nullptr);
  2033. // 2. Scroll to the beginning of the document for document. [CSSOMVIEW]
  2034. scroll_to_the_beginning_of_the_document();
  2035. // 3. Return.
  2036. return;
  2037. }
  2038. // 3. Otherwise:
  2039. else {
  2040. // 1. Assert: document's indicated part is an element.
  2041. VERIFY(indicated_part.has<Element*>());
  2042. // 2. Let target be document's indicated part.
  2043. auto target = indicated_part.get<Element*>();
  2044. // 3. Set document's target element to target.
  2045. set_target_element(target);
  2046. // FIXME: 4. Run the ancestor details revealing algorithm on target.
  2047. // FIXME: 5. Run the ancestor hidden-until-found revealing algorithm on target.
  2048. // 6. Scroll target into view, with behavior set to "auto", block set to "start", and inline set to "nearest". [CSSOMVIEW]
  2049. ScrollIntoViewOptions scroll_options;
  2050. scroll_options.block = Bindings::ScrollLogicalPosition::Start;
  2051. scroll_options.inline_ = Bindings::ScrollLogicalPosition::Nearest;
  2052. (void)target->scroll_into_view(scroll_options);
  2053. // 7. Run the focusing steps for target, with the Document's viewport as the fallback target.
  2054. // FIXME: Pass the Document's viewport somehow.
  2055. HTML::run_focusing_steps(target);
  2056. // FIXME: 8. Move the sequential focus navigation starting point to target.
  2057. }
  2058. }
  2059. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#try-to-scroll-to-the-fragment
  2060. void Document::try_to_scroll_to_the_fragment()
  2061. {
  2062. // FIXME: According to the spec we should only scroll here if document has no parser or parsing has stopped.
  2063. // It should be ok to remove this after we implement navigation events and scrolling will happen in
  2064. // "process scroll behavior".
  2065. // To try to scroll to the fragment for a Document document, perform the following steps in parallel:
  2066. // 1. Wait for an implementation-defined amount of time. (This is intended to allow the user agent to
  2067. // optimize the user experience in the face of performance concerns.)
  2068. // 2. Queue a global task on the navigation and traversal task source given document's relevant global
  2069. // object to run these steps:
  2070. // 1. If document has no parser, or its parser has stopped parsing, or the user agent has reason to
  2071. // believe the user is no longer interested in scrolling to the fragment, then abort these steps.
  2072. // 2. Scroll to the fragment given document.
  2073. // 3. If document's indicated part is still null, then try to scroll to the fragment for document.
  2074. scroll_to_the_fragment();
  2075. }
  2076. // https://drafts.csswg.org/cssom-view-1/#scroll-to-the-beginning-of-the-document
  2077. void Document::scroll_to_the_beginning_of_the_document()
  2078. {
  2079. // FIXME: Actually implement this algorithm
  2080. if (auto navigable = this->navigable())
  2081. navigable->perform_scroll_of_viewport({ 0, 0 });
  2082. }
  2083. StringView Document::ready_state() const
  2084. {
  2085. switch (m_readiness) {
  2086. case HTML::DocumentReadyState::Loading:
  2087. return "loading"sv;
  2088. case HTML::DocumentReadyState::Interactive:
  2089. return "interactive"sv;
  2090. case HTML::DocumentReadyState::Complete:
  2091. return "complete"sv;
  2092. }
  2093. VERIFY_NOT_REACHED();
  2094. }
  2095. // https://html.spec.whatwg.org/multipage/dom.html#update-the-current-document-readiness
  2096. void Document::update_readiness(HTML::DocumentReadyState readiness_value)
  2097. {
  2098. // 1. If document's current document readiness equals readinessValue, then return.
  2099. if (m_readiness == readiness_value)
  2100. return;
  2101. // 2. Set document's current document readiness to readinessValue.
  2102. m_readiness = readiness_value;
  2103. // 3. If document is associated with an HTML parser, then:
  2104. if (m_parser) {
  2105. // 1. Let now be the current high resolution time given document's relevant global object.
  2106. auto now = HighResolutionTime::current_high_resolution_time(relevant_global_object(*this));
  2107. // 2. If readinessValue is "complete", and document's load timing info's DOM complete time is 0,
  2108. // then set document's load timing info's DOM complete time to now.
  2109. if (readiness_value == HTML::DocumentReadyState::Complete && m_load_timing_info.dom_complete_time == 0) {
  2110. m_load_timing_info.dom_complete_time = now;
  2111. }
  2112. // 3. Otherwise, if readinessValue is "interactive", and document's load timing info's DOM interactive time is 0,
  2113. // then set document's load timing info's DOM interactive time to now.
  2114. else if (readiness_value == HTML::DocumentReadyState::Interactive && m_load_timing_info.dom_interactive_time == 0) {
  2115. m_load_timing_info.dom_interactive_time = now;
  2116. }
  2117. }
  2118. // 4. Fire an event named readystatechange at document.
  2119. dispatch_event(Event::create(realm(), HTML::EventNames::readystatechange));
  2120. if (readiness_value == HTML::DocumentReadyState::Complete) {
  2121. auto navigable = this->navigable();
  2122. if (navigable && navigable->is_traversable()) {
  2123. if (!is_decoded_svg()) {
  2124. HTML::HTMLLinkElement::load_fallback_favicon_if_needed(*this).release_value_but_fixme_should_propagate_errors();
  2125. }
  2126. navigable->traversable_navigable()->page().client().page_did_finish_loading(url());
  2127. } else {
  2128. m_needs_to_call_page_did_load = true;
  2129. }
  2130. }
  2131. notify_each_document_observer([&](auto const& document_observer) {
  2132. return document_observer.document_readiness_observer();
  2133. },
  2134. m_readiness);
  2135. }
  2136. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-lastmodified
  2137. String Document::last_modified() const
  2138. {
  2139. // The lastModified attribute, on getting, must return the date and time of the Document's source file's
  2140. // last modification, in the user's local time zone, in the following format:
  2141. // 1. The month component of the date.
  2142. // 2. A U+002F SOLIDUS character (/).
  2143. // 3. The day component of the date.
  2144. // 4. A U+002F SOLIDUS character (/).
  2145. // 5. The year component of the date.
  2146. // 6. A U+0020 SPACE character.
  2147. // 7. The hours component of the time.
  2148. // 8. A U+003A COLON character (:).
  2149. // 9. The minutes component of the time.
  2150. // 10. A U+003A COLON character (:).
  2151. // 11. The seconds component of the time.
  2152. // The Document's source file's last modification date and time must be derived from relevant features
  2153. // of the networking protocols used, e.g. from the value of the HTTP `Last-Modified` header of the document,
  2154. // or from metadata in the file system for local files. If the last modification date and time are not known,
  2155. // the attribute must return the current date and time in the above format.
  2156. constexpr auto format_string = "%m/%d/%Y %H:%M:%S"sv;
  2157. if (m_last_modified.has_value())
  2158. return MUST(m_last_modified.value().to_string(format_string));
  2159. return MUST(Core::DateTime::now().to_string(format_string));
  2160. }
  2161. Page& Document::page()
  2162. {
  2163. return m_page;
  2164. }
  2165. Page const& Document::page() const
  2166. {
  2167. return m_page;
  2168. }
  2169. EventTarget* Document::get_parent(Event const& event)
  2170. {
  2171. if (event.type() == HTML::EventNames::load)
  2172. return nullptr;
  2173. return m_window;
  2174. }
  2175. // https://html.spec.whatwg.org/#completely-loaded
  2176. bool Document::is_completely_loaded() const
  2177. {
  2178. return m_completely_loaded_time.has_value();
  2179. }
  2180. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#completely-finish-loading
  2181. void Document::completely_finish_loading()
  2182. {
  2183. if (!navigable())
  2184. return;
  2185. ScopeGuard notify_observers = [this] {
  2186. notify_each_document_observer([&](auto const& document_observer) {
  2187. return document_observer.document_completely_loaded();
  2188. });
  2189. };
  2190. // 1. Assert: document's browsing context is non-null.
  2191. VERIFY(browsing_context());
  2192. // 2. Set document's completely loaded time to the current time.
  2193. m_completely_loaded_time = AK::UnixDateTime::now();
  2194. // NOTE: See the end of shared_declarative_refresh_steps.
  2195. if (m_active_refresh_timer)
  2196. m_active_refresh_timer->start();
  2197. // 3. Let container be document's browsing context's container.
  2198. if (!navigable()->container())
  2199. return;
  2200. auto container = GC::make_root(navigable()->container());
  2201. // 4. If container is an iframe element, then queue an element task on the DOM manipulation task source given container to run the iframe load event steps given container.
  2202. if (container && is<HTML::HTMLIFrameElement>(*container)) {
  2203. container->queue_an_element_task(HTML::Task::Source::DOMManipulation, [container] {
  2204. run_iframe_load_event_steps(static_cast<HTML::HTMLIFrameElement&>(*container));
  2205. });
  2206. }
  2207. // 5. Otherwise, if container is non-null, then queue an element task on the DOM manipulation task source given container to fire an event named load at container.
  2208. else if (container) {
  2209. container->queue_an_element_task(HTML::Task::Source::DOMManipulation, [container] {
  2210. container->dispatch_event(DOM::Event::create(container->realm(), HTML::EventNames::load));
  2211. });
  2212. }
  2213. }
  2214. // https://html.spec.whatwg.org/#dom-document-cookie
  2215. WebIDL::ExceptionOr<String> Document::cookie(Cookie::Source source)
  2216. {
  2217. // On getting, if the document is a cookie-averse Document object, then the user agent must return the empty string.
  2218. if (is_cookie_averse())
  2219. return String {};
  2220. // Otherwise, if the Document's origin is an opaque origin, the user agent must throw a "SecurityError" DOMException.
  2221. if (origin().is_opaque())
  2222. return WebIDL::SecurityError::create(realm(), "Document origin is opaque"_string);
  2223. // Otherwise, the user agent must return the cookie-string for the document's URL for a "non-HTTP" API, decoded using
  2224. // UTF-8 decode without BOM.
  2225. return page().client().page_did_request_cookie(m_url, source);
  2226. }
  2227. // https://html.spec.whatwg.org/#dom-document-cookie
  2228. WebIDL::ExceptionOr<void> Document::set_cookie(StringView cookie_string, Cookie::Source source)
  2229. {
  2230. // On setting, if the document is a cookie-averse Document object, then the user agent must do nothing.
  2231. if (is_cookie_averse())
  2232. return {};
  2233. // Otherwise, if the Document's origin is an opaque origin, the user agent must throw a "SecurityError" DOMException.
  2234. if (origin().is_opaque())
  2235. return WebIDL::SecurityError::create(realm(), "Document origin is opaque"_string);
  2236. // Otherwise, the user agent must act as it would when receiving a set-cookie-string for the document's URL via a
  2237. // "non-HTTP" API, consisting of the new value encoded as UTF-8.
  2238. if (auto cookie = Cookie::parse_cookie(url(), cookie_string); cookie.has_value())
  2239. page().client().page_did_set_cookie(m_url, cookie.value(), source);
  2240. return {};
  2241. }
  2242. // https://html.spec.whatwg.org/#cookie-averse-document-object
  2243. bool Document::is_cookie_averse() const
  2244. {
  2245. // A Document object that falls into one of the following conditions is a cookie-averse Document object:
  2246. // * A Document object whose browsing context is null.
  2247. if (!browsing_context())
  2248. return true;
  2249. // * A Document whose URL's scheme is not an HTTP(S) scheme.
  2250. if (!url().scheme().is_one_of("http"sv, "https"sv)) {
  2251. // AD-HOC: This allows us to write cookie integration tests.
  2252. if (!m_enable_cookies_on_file_domains || url().scheme() != "file"sv)
  2253. return true;
  2254. }
  2255. return false;
  2256. }
  2257. String Document::fg_color() const
  2258. {
  2259. if (auto* body_element = body(); body_element && !is<HTML::HTMLFrameSetElement>(*body_element))
  2260. return body_element->get_attribute_value(HTML::AttributeNames::text);
  2261. return ""_string;
  2262. }
  2263. void Document::set_fg_color(String const& value)
  2264. {
  2265. if (auto* body_element = body(); body_element && !is<HTML::HTMLFrameSetElement>(*body_element))
  2266. MUST(body_element->set_attribute(HTML::AttributeNames::text, value));
  2267. }
  2268. String Document::link_color() const
  2269. {
  2270. if (auto* body_element = body(); body_element && !is<HTML::HTMLFrameSetElement>(*body_element))
  2271. return body_element->get_attribute_value(HTML::AttributeNames::link);
  2272. return ""_string;
  2273. }
  2274. void Document::set_link_color(String const& value)
  2275. {
  2276. if (auto* body_element = body(); body_element && !is<HTML::HTMLFrameSetElement>(*body_element))
  2277. MUST(body_element->set_attribute(HTML::AttributeNames::link, value));
  2278. }
  2279. String Document::vlink_color() const
  2280. {
  2281. if (auto* body_element = body(); body_element && !is<HTML::HTMLFrameSetElement>(*body_element))
  2282. return body_element->get_attribute_value(HTML::AttributeNames::vlink);
  2283. return ""_string;
  2284. }
  2285. void Document::set_vlink_color(String const& value)
  2286. {
  2287. if (auto* body_element = body(); body_element && !is<HTML::HTMLFrameSetElement>(*body_element))
  2288. MUST(body_element->set_attribute(HTML::AttributeNames::vlink, value));
  2289. }
  2290. String Document::alink_color() const
  2291. {
  2292. if (auto* body_element = body(); body_element && !is<HTML::HTMLFrameSetElement>(*body_element))
  2293. return body_element->get_attribute_value(HTML::AttributeNames::alink);
  2294. return ""_string;
  2295. }
  2296. void Document::set_alink_color(String const& value)
  2297. {
  2298. if (auto* body_element = body(); body_element && !is<HTML::HTMLFrameSetElement>(*body_element))
  2299. MUST(body_element->set_attribute(HTML::AttributeNames::alink, value));
  2300. }
  2301. String Document::bg_color() const
  2302. {
  2303. if (auto* body_element = body(); body_element && !is<HTML::HTMLFrameSetElement>(*body_element))
  2304. return body_element->get_attribute_value(HTML::AttributeNames::bgcolor);
  2305. return ""_string;
  2306. }
  2307. void Document::set_bg_color(String const& value)
  2308. {
  2309. if (auto* body_element = body(); body_element && !is<HTML::HTMLFrameSetElement>(*body_element))
  2310. MUST(body_element->set_attribute(HTML::AttributeNames::bgcolor, value));
  2311. }
  2312. String Document::dump_dom_tree_as_json() const
  2313. {
  2314. StringBuilder builder;
  2315. auto json = MUST(JsonObjectSerializer<>::try_create(builder));
  2316. serialize_tree_as_json(json);
  2317. MUST(json.finish());
  2318. return MUST(builder.to_string());
  2319. }
  2320. // https://html.spec.whatwg.org/multipage/semantics.html#has-a-style-sheet-that-is-blocking-scripts
  2321. bool Document::has_a_style_sheet_that_is_blocking_scripts() const
  2322. {
  2323. // FIXME: 1. If document's script-blocking style sheet set is not empty, then return true.
  2324. if (m_script_blocking_style_sheet_counter > 0)
  2325. return true;
  2326. // 2. If document's node navigable is null, then return false.
  2327. if (!navigable())
  2328. return false;
  2329. // 3. Let containerDocument be document's node navigable's container document.
  2330. auto container_document = navigable()->container_document();
  2331. // FIXME: 4. If containerDocument is non-null and containerDocument's script-blocking style sheet set is not empty, then return true.
  2332. if (container_document && container_document->m_script_blocking_style_sheet_counter > 0)
  2333. return true;
  2334. // 5. Return false
  2335. return false;
  2336. }
  2337. String Document::referrer() const
  2338. {
  2339. return m_referrer;
  2340. }
  2341. void Document::set_referrer(String referrer)
  2342. {
  2343. m_referrer = move(referrer);
  2344. }
  2345. // https://html.spec.whatwg.org/multipage/document-sequences.html#fully-active
  2346. bool Document::is_fully_active() const
  2347. {
  2348. // A Document d is said to be fully active when d is the active document of a navigable navigable, and either
  2349. // navigable is a top-level traversable or navigable's container document is fully active.
  2350. auto navigable = this->navigable();
  2351. if (!navigable)
  2352. return false;
  2353. auto traversable = navigable->traversable_navigable();
  2354. if (navigable == traversable && traversable->is_top_level_traversable())
  2355. return true;
  2356. auto container_document = navigable->container_document();
  2357. if (container_document && container_document != this && container_document->is_fully_active())
  2358. return true;
  2359. return false;
  2360. }
  2361. bool Document::is_active() const
  2362. {
  2363. auto navigable = this->navigable();
  2364. return navigable && navigable->active_document() == this;
  2365. }
  2366. // https://html.spec.whatwg.org/multipage/history.html#dom-document-location
  2367. GC::Ptr<HTML::Location> Document::location()
  2368. {
  2369. // The Document object's location attribute's getter must return this Document object's relevant global object's Location object,
  2370. // if this Document object is fully active, and null otherwise.
  2371. if (!is_fully_active())
  2372. return nullptr;
  2373. return window()->location();
  2374. }
  2375. // https://html.spec.whatwg.org/multipage/interaction.html#dom-document-hidden
  2376. bool Document::hidden() const
  2377. {
  2378. return m_visibility_state == HTML::VisibilityState::Hidden;
  2379. }
  2380. // https://html.spec.whatwg.org/multipage/interaction.html#dom-document-visibilitystate
  2381. StringView Document::visibility_state() const
  2382. {
  2383. switch (m_visibility_state) {
  2384. case HTML::VisibilityState::Hidden:
  2385. return "hidden"sv;
  2386. case HTML::VisibilityState::Visible:
  2387. return "visible"sv;
  2388. }
  2389. VERIFY_NOT_REACHED();
  2390. }
  2391. void Document::set_visibility_state(Badge<HTML::BrowsingContext>, HTML::VisibilityState visibility_state)
  2392. {
  2393. m_visibility_state = visibility_state;
  2394. }
  2395. // https://html.spec.whatwg.org/multipage/interaction.html#update-the-visibility-state
  2396. void Document::update_the_visibility_state(HTML::VisibilityState visibility_state)
  2397. {
  2398. // 1. If document's visibility state equals visibilityState, then return.
  2399. if (m_visibility_state == visibility_state)
  2400. return;
  2401. // 2. Set document's visibility state to visibilityState.
  2402. m_visibility_state = visibility_state;
  2403. // 3. Run any page visibility change steps which may be defined in other specifications, with visibility state and document.
  2404. notify_each_document_observer([&](auto const& document_observer) {
  2405. return document_observer.document_visibility_state_observer();
  2406. },
  2407. m_visibility_state);
  2408. // 4. Fire an event named visibilitychange at document, with its bubbles attribute initialized to true.
  2409. auto event = DOM::Event::create(realm(), HTML::EventNames::visibilitychange);
  2410. event->set_bubbles(true);
  2411. dispatch_event(event);
  2412. }
  2413. // https://drafts.csswg.org/cssom-view/#run-the-resize-steps
  2414. void Document::run_the_resize_steps()
  2415. {
  2416. // 1. If doc’s viewport has had its width or height changed
  2417. // (e.g. as a result of the user resizing the browser window, or changing the page zoom scale factor,
  2418. // or an iframe element’s dimensions are changed) since the last time these steps were run,
  2419. // fire an event named resize at the Window object associated with doc.
  2420. auto viewport_size = viewport_rect().size().to_type<int>();
  2421. bool is_initial_size = !m_last_viewport_size.has_value();
  2422. if (m_last_viewport_size == viewport_size)
  2423. return;
  2424. m_last_viewport_size = viewport_size;
  2425. if (!is_initial_size)
  2426. window()->dispatch_event(DOM::Event::create(realm(), UIEvents::EventNames::resize));
  2427. schedule_layout_update();
  2428. }
  2429. // https://w3c.github.io/csswg-drafts/cssom-view-1/#document-run-the-scroll-steps
  2430. void Document::run_the_scroll_steps()
  2431. {
  2432. // 1. For each item target in doc’s pending scroll event targets, in the order they were added to the list, run these substeps:
  2433. for (auto& target : m_pending_scroll_event_targets) {
  2434. // 1. If target is a Document, fire an event named scroll that bubbles at target and fire an event named scroll at the VisualViewport that is associated with target.
  2435. if (is<Document>(*target)) {
  2436. auto event = DOM::Event::create(realm(), HTML::EventNames::scroll);
  2437. event->set_bubbles(true);
  2438. target->dispatch_event(event);
  2439. // FIXME: Fire at the associated VisualViewport
  2440. }
  2441. // 2. Otherwise, fire an event named scroll at target.
  2442. else {
  2443. auto event = DOM::Event::create(realm(), HTML::EventNames::scroll);
  2444. target->dispatch_event(event);
  2445. }
  2446. }
  2447. // 2. Empty doc’s pending scroll event targets.
  2448. m_pending_scroll_event_targets.clear();
  2449. }
  2450. void Document::add_media_query_list(GC::Ref<CSS::MediaQueryList> media_query_list)
  2451. {
  2452. m_media_query_lists.append(*media_query_list);
  2453. }
  2454. // https://drafts.csswg.org/cssom-view/#evaluate-media-queries-and-report-changes
  2455. void Document::evaluate_media_queries_and_report_changes()
  2456. {
  2457. // NOTE: Not in the spec, but we take this opportunity to prune null WeakPtrs.
  2458. m_media_query_lists.remove_all_matching([](auto& it) {
  2459. return it.is_null();
  2460. });
  2461. // 1. For each MediaQueryList object target that has doc as its document,
  2462. // in the order they were created, oldest first, run these substeps:
  2463. for (auto& media_query_list_ptr : m_media_query_lists) {
  2464. // 1. If target’s matches state has changed since the last time these steps
  2465. // were run, fire an event at target using the MediaQueryListEvent constructor,
  2466. // with its type attribute initialized to change, its isTrusted attribute
  2467. // initialized to true, its media attribute initialized to target’s media,
  2468. // and its matches attribute initialized to target’s matches state.
  2469. if (media_query_list_ptr.is_null())
  2470. continue;
  2471. GC::Ptr<CSS::MediaQueryList> media_query_list = media_query_list_ptr.ptr();
  2472. bool did_match = media_query_list->matches();
  2473. bool now_matches = media_query_list->evaluate();
  2474. if (did_match != now_matches) {
  2475. CSS::MediaQueryListEventInit init;
  2476. init.media = media_query_list->media();
  2477. init.matches = now_matches;
  2478. auto event = CSS::MediaQueryListEvent::create(realm(), HTML::EventNames::change, init);
  2479. event->set_is_trusted(true);
  2480. media_query_list->dispatch_event(*event);
  2481. }
  2482. }
  2483. // Also not in the spec, but this is as good a place as any to evaluate @media rules!
  2484. evaluate_media_rules();
  2485. }
  2486. void Document::evaluate_media_rules()
  2487. {
  2488. auto window = this->window();
  2489. if (!window)
  2490. return;
  2491. bool any_media_queries_changed_match_state = false;
  2492. for_each_active_css_style_sheet([&](CSS::CSSStyleSheet& style_sheet, auto) {
  2493. if (style_sheet.evaluate_media_queries(*window))
  2494. any_media_queries_changed_match_state = true;
  2495. });
  2496. if (any_media_queries_changed_match_state) {
  2497. style_computer().invalidate_rule_cache();
  2498. invalidate_style(StyleInvalidationReason::MediaQueryChangedMatchState);
  2499. invalidate_layout_tree();
  2500. }
  2501. }
  2502. DOMImplementation* Document::implementation()
  2503. {
  2504. if (!m_implementation)
  2505. m_implementation = DOMImplementation::create(*this);
  2506. return m_implementation;
  2507. }
  2508. bool Document::has_focus() const
  2509. {
  2510. // FIXME: Return whether we actually have focus.
  2511. return true;
  2512. }
  2513. void Document::set_parser(Badge<HTML::HTMLParser>, HTML::HTMLParser& parser)
  2514. {
  2515. m_parser = parser;
  2516. }
  2517. void Document::detach_parser(Badge<HTML::HTMLParser>)
  2518. {
  2519. m_parser = nullptr;
  2520. }
  2521. // https://www.w3.org/TR/xml/#NT-NameStartChar
  2522. static bool is_valid_name_start_character(u32 code_point)
  2523. {
  2524. return code_point == ':'
  2525. || (code_point >= 'A' && code_point <= 'Z')
  2526. || code_point == '_'
  2527. || (code_point >= 'a' && code_point <= 'z')
  2528. || (code_point >= 0xc0 && code_point <= 0xd6)
  2529. || (code_point >= 0xd8 && code_point <= 0xf6)
  2530. || (code_point >= 0xf8 && code_point <= 0x2ff)
  2531. || (code_point >= 0x370 && code_point <= 0x37d)
  2532. || (code_point >= 0x37f && code_point <= 0x1fff)
  2533. || (code_point >= 0x200c && code_point <= 0x200d)
  2534. || (code_point >= 0x2070 && code_point <= 0x218f)
  2535. || (code_point >= 0x2c00 && code_point <= 0x2fef)
  2536. || (code_point >= 0x3001 && code_point <= 0xD7ff)
  2537. || (code_point >= 0xf900 && code_point <= 0xfdcf)
  2538. || (code_point >= 0xfdf0 && code_point <= 0xfffd)
  2539. || (code_point >= 0x10000 && code_point <= 0xeffff);
  2540. }
  2541. // https://www.w3.org/TR/xml/#NT-NameChar
  2542. static inline bool is_valid_name_character(u32 code_point)
  2543. {
  2544. return is_valid_name_start_character(code_point)
  2545. || code_point == '-'
  2546. || code_point == '.'
  2547. || (code_point >= '0' && code_point <= '9')
  2548. || code_point == 0xb7
  2549. || (code_point >= 0x300 && code_point <= 0x36f)
  2550. || (code_point >= 0x203f && code_point <= 0x2040);
  2551. }
  2552. // https://www.w3.org/TR/xml/#NT-Name
  2553. bool Document::is_valid_name(String const& name)
  2554. {
  2555. if (name.is_empty())
  2556. return false;
  2557. auto code_points = name.code_points();
  2558. auto it = code_points.begin();
  2559. if (!is_valid_name_start_character(*it))
  2560. return false;
  2561. ++it;
  2562. for (; it != code_points.end(); ++it) {
  2563. if (!is_valid_name_character(*it))
  2564. return false;
  2565. }
  2566. return true;
  2567. }
  2568. // https://dom.spec.whatwg.org/#validate
  2569. WebIDL::ExceptionOr<Document::PrefixAndTagName> Document::validate_qualified_name(JS::Realm& realm, FlyString const& qualified_name)
  2570. {
  2571. if (qualified_name.is_empty())
  2572. return WebIDL::InvalidCharacterError::create(realm, "Empty string is not a valid qualified name."_string);
  2573. auto utf8view = qualified_name.code_points();
  2574. Optional<size_t> colon_offset;
  2575. bool at_start_of_name = true;
  2576. for (auto it = utf8view.begin(); it != utf8view.end(); ++it) {
  2577. auto code_point = *it;
  2578. if (code_point == ':') {
  2579. if (colon_offset.has_value())
  2580. return WebIDL::InvalidCharacterError::create(realm, "More than one colon (:) in qualified name."_string);
  2581. colon_offset = utf8view.byte_offset_of(it);
  2582. at_start_of_name = true;
  2583. continue;
  2584. }
  2585. if (at_start_of_name) {
  2586. if (!is_valid_name_start_character(code_point))
  2587. return WebIDL::InvalidCharacterError::create(realm, "Invalid start of qualified name."_string);
  2588. at_start_of_name = false;
  2589. continue;
  2590. }
  2591. if (!is_valid_name_character(code_point))
  2592. return WebIDL::InvalidCharacterError::create(realm, "Invalid character in qualified name."_string);
  2593. }
  2594. if (!colon_offset.has_value())
  2595. return Document::PrefixAndTagName {
  2596. .prefix = {},
  2597. .tag_name = qualified_name,
  2598. };
  2599. if (*colon_offset == 0)
  2600. return WebIDL::InvalidCharacterError::create(realm, "Qualified name can't start with colon (:)."_string);
  2601. if (*colon_offset >= (qualified_name.bytes_as_string_view().length() - 1))
  2602. return WebIDL::InvalidCharacterError::create(realm, "Qualified name can't end with colon (:)."_string);
  2603. return Document::PrefixAndTagName {
  2604. .prefix = MUST(FlyString::from_utf8(qualified_name.bytes_as_string_view().substring_view(0, *colon_offset))),
  2605. .tag_name = MUST(FlyString::from_utf8(qualified_name.bytes_as_string_view().substring_view(*colon_offset + 1))),
  2606. };
  2607. }
  2608. // https://dom.spec.whatwg.org/#dom-document-createnodeiterator
  2609. GC::Ref<NodeIterator> Document::create_node_iterator(Node& root, unsigned what_to_show, GC::Ptr<NodeFilter> filter)
  2610. {
  2611. return NodeIterator::create(root, what_to_show, filter).release_value_but_fixme_should_propagate_errors();
  2612. }
  2613. // https://dom.spec.whatwg.org/#dom-document-createtreewalker
  2614. GC::Ref<TreeWalker> Document::create_tree_walker(Node& root, unsigned what_to_show, GC::Ptr<NodeFilter> filter)
  2615. {
  2616. return TreeWalker::create(root, what_to_show, filter);
  2617. }
  2618. void Document::register_node_iterator(Badge<NodeIterator>, NodeIterator& node_iterator)
  2619. {
  2620. auto result = m_node_iterators.set(&node_iterator);
  2621. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  2622. }
  2623. void Document::unregister_node_iterator(Badge<NodeIterator>, NodeIterator& node_iterator)
  2624. {
  2625. bool was_removed = m_node_iterators.remove(&node_iterator);
  2626. VERIFY(was_removed);
  2627. }
  2628. void Document::register_document_observer(Badge<DocumentObserver>, DocumentObserver& document_observer)
  2629. {
  2630. auto result = m_document_observers.set(document_observer);
  2631. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  2632. }
  2633. void Document::unregister_document_observer(Badge<DocumentObserver>, DocumentObserver& document_observer)
  2634. {
  2635. bool was_removed = m_document_observers.remove(document_observer);
  2636. VERIFY(was_removed);
  2637. }
  2638. void Document::increment_number_of_things_delaying_the_load_event(Badge<DocumentLoadEventDelayer>)
  2639. {
  2640. ++m_number_of_things_delaying_the_load_event;
  2641. page().client().page_did_update_resource_count(m_number_of_things_delaying_the_load_event);
  2642. }
  2643. void Document::decrement_number_of_things_delaying_the_load_event(Badge<DocumentLoadEventDelayer>)
  2644. {
  2645. VERIFY(m_number_of_things_delaying_the_load_event);
  2646. --m_number_of_things_delaying_the_load_event;
  2647. page().client().page_did_update_resource_count(m_number_of_things_delaying_the_load_event);
  2648. }
  2649. bool Document::anything_is_delaying_the_load_event() const
  2650. {
  2651. if (m_number_of_things_delaying_the_load_event > 0)
  2652. return true;
  2653. for (auto& navigable : descendant_navigables()) {
  2654. if (navigable->container()->currently_delays_the_load_event())
  2655. return true;
  2656. }
  2657. // FIXME: Track down anything else that is supposed to delay the load event.
  2658. return false;
  2659. }
  2660. void Document::set_page_showing(bool page_showing)
  2661. {
  2662. if (m_page_showing == page_showing)
  2663. return;
  2664. m_page_showing = page_showing;
  2665. notify_each_document_observer([&](auto const& document_observer) {
  2666. return document_observer.document_page_showing_observer();
  2667. },
  2668. m_page_showing);
  2669. }
  2670. void Document::invalidate_stacking_context_tree()
  2671. {
  2672. if (auto* paintable_box = this->paintable_box())
  2673. paintable_box->invalidate_stacking_context();
  2674. }
  2675. void Document::check_favicon_after_loading_link_resource()
  2676. {
  2677. // https://html.spec.whatwg.org/multipage/links.html#rel-icon
  2678. // NOTE: firefox also load favicons outside the head tag, which is against spec (see table 4.6.7)
  2679. auto* head_element = head();
  2680. if (!head_element)
  2681. return;
  2682. auto favicon_link_elements = HTMLCollection::create(*head_element, HTMLCollection::Scope::Descendants, [](Element const& element) {
  2683. if (!is<HTML::HTMLLinkElement>(element))
  2684. return false;
  2685. return static_cast<HTML::HTMLLinkElement const&>(element).has_loaded_icon();
  2686. });
  2687. if (favicon_link_elements->length() == 0) {
  2688. dbgln_if(SPAM_DEBUG, "No favicon found to be used");
  2689. return;
  2690. }
  2691. // 4.6.7.8 Link type "icon"
  2692. //
  2693. // If there are multiple equally appropriate icons, user agents must use the last one declared
  2694. // in tree order at the time that the user agent collected the list of icons.
  2695. //
  2696. // If multiple icons are provided, the user agent must select the most appropriate icon
  2697. // according to the type, media, and sizes attributes.
  2698. //
  2699. // FIXME: There is no selective behavior yet for favicons.
  2700. for (auto i = favicon_link_elements->length(); i-- > 0;) {
  2701. auto favicon_element = favicon_link_elements->item(i);
  2702. if (favicon_element == m_active_element.ptr())
  2703. return;
  2704. // If the user agent tries to use an icon but that icon is determined, upon closer examination,
  2705. // to in fact be inappropriate (...), then the user agent must try the next-most-appropriate icon
  2706. // as determined by the attributes.
  2707. if (static_cast<HTML::HTMLLinkElement*>(favicon_element)->load_favicon_and_use_if_window_is_active()) {
  2708. m_active_favicon = favicon_element;
  2709. return;
  2710. }
  2711. }
  2712. dbgln_if(SPAM_DEBUG, "No favicon found to be used");
  2713. }
  2714. void Document::set_window(HTML::Window& window)
  2715. {
  2716. m_window = &window;
  2717. }
  2718. // https://html.spec.whatwg.org/multipage/custom-elements.html#look-up-a-custom-element-definition
  2719. GC::Ptr<HTML::CustomElementDefinition> Document::lookup_custom_element_definition(Optional<FlyString> const& namespace_, FlyString const& local_name, Optional<String> const& is) const
  2720. {
  2721. // 1. If namespace is not the HTML namespace, then return null.
  2722. if (namespace_ != Namespace::HTML)
  2723. return nullptr;
  2724. // 2. If document's browsing context is null, then return null.
  2725. if (!browsing_context())
  2726. return nullptr;
  2727. // 3. Let registry be document's relevant global object's custom element registry.
  2728. auto registry = verify_cast<HTML::Window>(relevant_global_object(*this)).custom_elements();
  2729. // 4. If registry's custom element definition set contains an item with name and local name both equal to localName, then return that item.
  2730. auto converted_local_name = local_name.to_string();
  2731. auto maybe_definition = registry->get_definition_with_name_and_local_name(converted_local_name, converted_local_name);
  2732. if (maybe_definition)
  2733. return maybe_definition;
  2734. // 5. If registry's custom element definition set contains an item with name equal to is and local name equal to localName, then return that item.
  2735. // 6. Return null.
  2736. // NOTE: If `is` has no value, it can never match as custom element definitions always have a name and localName (i.e. not stored as Optional<String>)
  2737. if (!is.has_value())
  2738. return nullptr;
  2739. return registry->get_definition_with_name_and_local_name(is.value(), converted_local_name);
  2740. }
  2741. CSS::StyleSheetList& Document::style_sheets()
  2742. {
  2743. if (!m_style_sheets)
  2744. m_style_sheets = CSS::StyleSheetList::create(*this);
  2745. return *m_style_sheets;
  2746. }
  2747. CSS::StyleSheetList const& Document::style_sheets() const
  2748. {
  2749. return const_cast<Document*>(this)->style_sheets();
  2750. }
  2751. GC::Ref<HTML::History> Document::history()
  2752. {
  2753. if (!m_history)
  2754. m_history = HTML::History::create(realm(), *this);
  2755. return *m_history;
  2756. }
  2757. GC::Ref<HTML::History> Document::history() const
  2758. {
  2759. return const_cast<Document*>(this)->history();
  2760. }
  2761. // https://html.spec.whatwg.org/multipage/origin.html#dom-document-domain
  2762. String Document::domain() const
  2763. {
  2764. // 1. Let effectiveDomain be this's origin's effective domain.
  2765. auto effective_domain = origin().effective_domain();
  2766. // 2. If effectiveDomain is null, then return the empty string.
  2767. if (!effective_domain.has_value())
  2768. return String {};
  2769. // 3. Return effectiveDomain, serialized.
  2770. return effective_domain->serialize();
  2771. }
  2772. void Document::set_domain(String const& domain)
  2773. {
  2774. dbgln("(STUBBED) Document::set_domain(domain='{}')", domain);
  2775. }
  2776. void Document::set_navigation_id(Optional<String> navigation_id)
  2777. {
  2778. m_navigation_id = move(navigation_id);
  2779. }
  2780. Optional<String> Document::navigation_id() const
  2781. {
  2782. return m_navigation_id;
  2783. }
  2784. HTML::SandboxingFlagSet Document::active_sandboxing_flag_set() const
  2785. {
  2786. return m_active_sandboxing_flag_set;
  2787. }
  2788. void Document::set_active_sandboxing_flag_set(HTML::SandboxingFlagSet sandboxing_flag_set)
  2789. {
  2790. m_active_sandboxing_flag_set = sandboxing_flag_set;
  2791. }
  2792. HTML::PolicyContainer Document::policy_container() const
  2793. {
  2794. return m_policy_container;
  2795. }
  2796. void Document::set_policy_container(HTML::PolicyContainer policy_container)
  2797. {
  2798. m_policy_container = move(policy_container);
  2799. }
  2800. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#snapshotting-source-snapshot-params
  2801. HTML::SourceSnapshotParams Document::snapshot_source_snapshot_params() const
  2802. {
  2803. // To snapshot source snapshot params given a Document sourceDocument, return a new source snapshot params with
  2804. // has transient activation
  2805. // true if sourceDocument's relevant global object has transient activation; otherwise false
  2806. // sandboxing flags
  2807. // sourceDocument's active sandboxing flag set
  2808. // allows downloading
  2809. // false if sourceDocument's active sandboxing flag set has the sandboxed downloads browsing context flag set; otherwise true
  2810. // fetch client
  2811. // sourceDocument's relevant settings object
  2812. // source policy container
  2813. // sourceDocument's policy container
  2814. return HTML::SourceSnapshotParams {
  2815. .has_transient_activation = verify_cast<HTML::Window>(HTML::relevant_global_object(*this)).has_transient_activation(),
  2816. .sandboxing_flags = m_active_sandboxing_flag_set,
  2817. .allows_downloading = !has_flag(m_active_sandboxing_flag_set, HTML::SandboxingFlagSet::SandboxedDownloads),
  2818. .fetch_client = relevant_settings_object(),
  2819. .source_policy_container = m_policy_container
  2820. };
  2821. }
  2822. // https://html.spec.whatwg.org/multipage/document-sequences.html#descendant-navigables
  2823. Vector<GC::Root<HTML::Navigable>> Document::descendant_navigables()
  2824. {
  2825. // 1. Let navigables be new list.
  2826. Vector<GC::Root<HTML::Navigable>> navigables;
  2827. // 2. Let navigableContainers be a list of all shadow-including descendants of document that are navigable containers, in shadow-including tree order.
  2828. // 3. For each navigableContainer of navigableContainers:
  2829. for_each_shadow_including_descendant([&](DOM::Node& node) {
  2830. if (is<HTML::NavigableContainer>(node)) {
  2831. auto& navigable_container = static_cast<HTML::NavigableContainer&>(node);
  2832. // 1. If navigableContainer's content navigable is null, then continue.
  2833. if (!navigable_container.content_navigable())
  2834. return TraversalDecision::Continue;
  2835. // 2. Extend navigables with navigableContainer's content navigable's active document's inclusive descendant navigables.
  2836. auto document = navigable_container.content_navigable()->active_document();
  2837. // AD-HOC: If the descendant navigable doesn't have an active document, just skip over it.
  2838. if (!document)
  2839. return TraversalDecision::Continue;
  2840. navigables.extend(document->inclusive_descendant_navigables());
  2841. }
  2842. return TraversalDecision::Continue;
  2843. });
  2844. // 4. Return navigables.
  2845. return navigables;
  2846. }
  2847. Vector<GC::Root<HTML::Navigable>> const Document::descendant_navigables() const
  2848. {
  2849. return const_cast<Document&>(*this).descendant_navigables();
  2850. }
  2851. // https://html.spec.whatwg.org/multipage/document-sequences.html#inclusive-descendant-navigables
  2852. Vector<GC::Root<HTML::Navigable>> Document::inclusive_descendant_navigables()
  2853. {
  2854. // 1. Let navigables be « document's node navigable ».
  2855. Vector<GC::Root<HTML::Navigable>> navigables;
  2856. navigables.append(*navigable());
  2857. // 2. Extend navigables with document's descendant navigables.
  2858. navigables.extend(descendant_navigables());
  2859. // 3. Return navigables.
  2860. return navigables;
  2861. }
  2862. // https://html.spec.whatwg.org/multipage/document-sequences.html#ancestor-navigables
  2863. Vector<GC::Root<HTML::Navigable>> Document::ancestor_navigables()
  2864. {
  2865. // NOTE: This isn't in the spec, but if we don't have a navigable, we can't have ancestors either.
  2866. auto document_node_navigable = this->navigable();
  2867. if (!document_node_navigable)
  2868. return {};
  2869. // 1. Let navigable be document's node navigable's parent.
  2870. auto navigable = document_node_navigable->parent();
  2871. // 2. Let ancestors be an empty list.
  2872. Vector<GC::Root<HTML::Navigable>> ancestors;
  2873. // 3. While navigable is not null:
  2874. while (navigable) {
  2875. // 1. Prepend navigable to ancestors.
  2876. ancestors.prepend(*navigable);
  2877. // 2. Set navigable to navigable's parent.
  2878. navigable = navigable->parent();
  2879. }
  2880. // 4. Return ancestors.
  2881. return ancestors;
  2882. }
  2883. Vector<GC::Root<HTML::Navigable>> const Document::ancestor_navigables() const
  2884. {
  2885. return const_cast<Document&>(*this).ancestor_navigables();
  2886. }
  2887. // https://html.spec.whatwg.org/multipage/document-sequences.html#inclusive-ancestor-navigables
  2888. Vector<GC::Root<HTML::Navigable>> Document::inclusive_ancestor_navigables()
  2889. {
  2890. // 1. Let navigables be document's ancestor navigables.
  2891. auto navigables = ancestor_navigables();
  2892. // 2. Append document's node navigable to navigables.
  2893. navigables.append(*navigable());
  2894. // 3. Return navigables.
  2895. return navigables;
  2896. }
  2897. // https://html.spec.whatwg.org/multipage/document-sequences.html#document-tree-child-navigables
  2898. Vector<GC::Root<HTML::Navigable>> Document::document_tree_child_navigables()
  2899. {
  2900. // 1. If document's node navigable is null, then return the empty list.
  2901. if (!navigable())
  2902. return {};
  2903. // 2. Let navigables be new list.
  2904. Vector<GC::Root<HTML::Navigable>> navigables;
  2905. // 3. Let navigableContainers be a list of all descendants of document that are navigable containers, in tree order.
  2906. // 4. For each navigableContainer of navigableContainers:
  2907. for_each_in_subtree_of_type<HTML::NavigableContainer>([&](HTML::NavigableContainer& navigable_container) {
  2908. // 1. If navigableContainer's content navigable is null, then continue.
  2909. if (!navigable_container.content_navigable())
  2910. return TraversalDecision::Continue;
  2911. // 2. Append navigableContainer's content navigable to navigables.
  2912. navigables.append(*navigable_container.content_navigable());
  2913. return TraversalDecision::Continue;
  2914. });
  2915. // 5. Return navigables.
  2916. return navigables;
  2917. }
  2918. // https://html.spec.whatwg.org/multipage/document-lifecycle.html#unloading-document-cleanup-steps
  2919. void Document::run_unloading_cleanup_steps()
  2920. {
  2921. // 1. Let window be document's relevant global object.
  2922. auto* window = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&HTML::relevant_global_object(*this));
  2923. VERIFY(window);
  2924. // FIXME: 2. For each WebSocket object webSocket whose relevant global object is window, make disappear webSocket.
  2925. // If this affected any WebSocket objects, then set document's salvageable state to false.
  2926. // FIXME: 3. For each WebTransport object transport whose relevant global object is window, run the context cleanup steps given transport.
  2927. // 4. If document's salvageable state is false, then:
  2928. if (!m_salvageable) {
  2929. // 1. For each EventSource object eventSource whose relevant global object is equal to window, forcibly close eventSource.
  2930. window->forcibly_close_all_event_sources();
  2931. // 2. Clear window's map of active timers.
  2932. window->clear_map_of_active_timers();
  2933. }
  2934. FileAPI::run_unloading_cleanup_steps(*this);
  2935. }
  2936. // https://html.spec.whatwg.org/multipage/document-lifecycle.html#destroy-a-document
  2937. void Document::destroy()
  2938. {
  2939. // FIXME: 1. Assert: this is running as part of a task queued on document's relevant agent's event loop.
  2940. // 2. Abort document.
  2941. abort();
  2942. // 3. Set document's salvageable state to false.
  2943. m_salvageable = false;
  2944. // 4. Let ports be the list of MessagePorts whose relevant global object's associated Document is document.
  2945. // 5. For each port in ports, disentangle port.
  2946. HTML::MessagePort::for_each_message_port([&](HTML::MessagePort& port) {
  2947. auto& global = HTML::relevant_global_object(port);
  2948. if (!is<HTML::Window>(global))
  2949. return;
  2950. auto& window = static_cast<HTML::Window&>(global);
  2951. if (&window.associated_document() == this)
  2952. port.disentangle();
  2953. });
  2954. // 6. Run any unloading document cleanup steps for document that are defined by this specification and other applicable specifications.
  2955. run_unloading_cleanup_steps();
  2956. // 7. Remove any tasks whose document is document from any task queue (without running those tasks).
  2957. HTML::main_thread_event_loop().task_queue().remove_tasks_matching([this](auto& task) {
  2958. return task.document() == this;
  2959. });
  2960. // 8. Set document's browsing context to null.
  2961. m_browsing_context = nullptr;
  2962. // Not in the spec:
  2963. for (auto& navigable_container : HTML::NavigableContainer::all_instances()) {
  2964. if (&navigable_container->document() == this)
  2965. HTML::all_navigables().remove(navigable_container->content_navigable());
  2966. }
  2967. // 9. Set document's node navigable's active session history entry's document state's document to null.
  2968. if (auto navigable = this->navigable())
  2969. navigable->active_session_history_entry()->document_state()->set_document(nullptr);
  2970. // FIXME: 10. Remove document from the owner set of each WorkerGlobalScope object whose set contains document.
  2971. // FIXME: 11. For each workletGlobalScope in document's worklet global scopes, terminate workletGlobalScope.
  2972. }
  2973. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#make-document-unsalvageable
  2974. void Document::make_unsalvageable([[maybe_unused]] String reason)
  2975. {
  2976. // FIXME: 1. Let details be a new not restored reason details whose reason is reason.
  2977. // FIXME: 2. Append details to document's bfcache blocking details.
  2978. // 3. Set document's salvageable state to false.
  2979. set_salvageable(false);
  2980. }
  2981. // https://html.spec.whatwg.org/multipage/document-lifecycle.html#destroy-a-document-and-its-descendants
  2982. void Document::destroy_a_document_and_its_descendants(GC::Ptr<GC::Function<void()>> after_all_destruction)
  2983. {
  2984. // 1. If document is not fully active, then:
  2985. if (!is_fully_active()) {
  2986. // 1. Make document unsalvageable given document and "masked".
  2987. make_unsalvageable("masked"_string);
  2988. // FIXME: 2. If document's node navigable is a top-level traversable,
  2989. // build not restored reasons for a top-level traversable and its descendants given document's node navigable.
  2990. }
  2991. // 2. Let childNavigables be document's child navigables.
  2992. IGNORE_USE_IN_ESCAPING_LAMBDA auto child_navigables = document_tree_child_navigables();
  2993. // 3. Let numberDestroyed be 0.
  2994. IGNORE_USE_IN_ESCAPING_LAMBDA size_t number_destroyed = 0;
  2995. // 4. For each childNavigable of childNavigable's, queue a global task on the navigation and traversal task source
  2996. // given childNavigable's active window to perform the following steps:
  2997. for (auto& child_navigable : child_navigables) {
  2998. HTML::queue_global_task(HTML::Task::Source::NavigationAndTraversal, *child_navigable->active_window(), GC::create_function(heap(), [&heap = heap(), &number_destroyed, child_navigable = child_navigable.ptr()] {
  2999. // 1. Let incrementDestroyed be an algorithm step which increments numberDestroyed.
  3000. auto increment_destroyed = GC::create_function(heap, [&number_destroyed] { ++number_destroyed; });
  3001. // 2. Destroy a document and its descendants given childNavigable's active document and incrementDestroyed.
  3002. child_navigable->active_document()->destroy_a_document_and_its_descendants(move(increment_destroyed));
  3003. }));
  3004. }
  3005. // 5. Wait until numberDestroyed equals childNavigable's size.
  3006. HTML::main_thread_event_loop().spin_until(GC::create_function(heap(), [&] {
  3007. return number_destroyed == child_navigables.size();
  3008. }));
  3009. // 6. Queue a global task on the navigation and traversal task source given document's relevant global object to perform the following steps:
  3010. HTML::queue_global_task(HTML::Task::Source::NavigationAndTraversal, relevant_global_object(*this), GC::create_function(heap(), [after_all_destruction = move(after_all_destruction), this] {
  3011. // 1. Destroy document.
  3012. destroy();
  3013. // 2. If afterAllDestruction was given, then run it.
  3014. if (after_all_destruction)
  3015. after_all_destruction->function()();
  3016. }));
  3017. }
  3018. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#abort-a-document
  3019. void Document::abort()
  3020. {
  3021. // 1. Assert: this is running as part of a task queued on document's relevant agent's event loop.
  3022. // FIXME: 2. Cancel any instances of the fetch algorithm in the context of document,
  3023. // discarding any tasks queued for them, and discarding any further data received from the network for them.
  3024. // If this resulted in any instances of the fetch algorithm being canceled
  3025. // or any queued tasks or any network data getting discarded,
  3026. // then set document's salvageable state to false.
  3027. // 3. If document's during-loading navigation ID for WebDriver BiDi is non-null, then:
  3028. if (m_navigation_id.has_value()) {
  3029. // 1. FIXME: Invoke WebDriver BiDi navigation aborted with document's browsing context,
  3030. // and new WebDriver BiDi navigation status whose whose id is document's navigation id,
  3031. // status is "canceled", and url is document's URL.
  3032. // 2. Set document's during-loading navigation ID for WebDriver BiDi to null.
  3033. m_navigation_id = {};
  3034. }
  3035. // 4. If document has an active parser, then:
  3036. if (auto parser = active_parser()) {
  3037. // 1. Set document's active parser was aborted to true.
  3038. m_active_parser_was_aborted = true;
  3039. // 2. Abort that parser.
  3040. parser->abort();
  3041. // 3. Set document's salvageable state to false.
  3042. m_salvageable = false;
  3043. }
  3044. }
  3045. // https://html.spec.whatwg.org/multipage/document-lifecycle.html#abort-a-document-and-its-descendants
  3046. void Document::abort_a_document_and_its_descendants()
  3047. {
  3048. // FIXME 1. Assert: this is running as part of a task queued on document's relevant agent's event loop.
  3049. // 2. Let descendantNavigables be document's descendant navigables.
  3050. auto descendant_navigables = this->descendant_navigables();
  3051. // 3. For each descendantNavigable of descendantNavigables, queue a global task on the navigation and traversal task source given descendantNavigable's active window to perform the following steps:
  3052. for (auto& descendant_navigable : descendant_navigables) {
  3053. HTML::queue_global_task(HTML::Task::Source::NavigationAndTraversal, *descendant_navigable->active_window(), GC::create_function(heap(), [this, descendant_navigable = descendant_navigable.ptr()] {
  3054. // NOTE: This is not in the spec but we need to abort ongoing navigations in all descendant navigables.
  3055. // See https://github.com/whatwg/html/issues/9711
  3056. descendant_navigable->set_ongoing_navigation({});
  3057. // 1. Abort descendantNavigable's active document.
  3058. descendant_navigable->active_document()->abort();
  3059. // 2. If descendantNavigable's active document's salvageable is false, then set document's salvageable to false.
  3060. if (!descendant_navigable->active_document()->m_salvageable)
  3061. m_salvageable = false;
  3062. }));
  3063. }
  3064. // 4. Abort document.
  3065. abort();
  3066. }
  3067. // https://html.spec.whatwg.org/multipage/dom.html#active-parser
  3068. GC::Ptr<HTML::HTMLParser> Document::active_parser()
  3069. {
  3070. if (!m_parser)
  3071. return nullptr;
  3072. if (m_parser->aborted() || m_parser->stopped())
  3073. return nullptr;
  3074. return m_parser;
  3075. }
  3076. void Document::set_browsing_context(HTML::BrowsingContext* browsing_context)
  3077. {
  3078. m_browsing_context = browsing_context;
  3079. }
  3080. // https://html.spec.whatwg.org/multipage/document-lifecycle.html#unload-a-document
  3081. void Document::unload(GC::Ptr<Document>)
  3082. {
  3083. // FIXME: 1. Assert: this is running as part of a task queued on oldDocument's event loop.
  3084. // FIXME: 2. Let unloadTimingInfo be a new document unload timing info.
  3085. // FIXME: 3. If newDocument is not given, then set unloadTimingInfo to null.
  3086. // FIXME: 4. Otherwise, if newDocument's event loop is not oldDocument's event loop, then the user agent may be unloading oldDocument in parallel. In that case, the user agent should
  3087. // set unloadTimingInfo to null.
  3088. // 5. Let intendToStoreInBfcache be true if the user agent intends to keep oldDocument alive in a session history entry, such that it can later be used for history traversal.
  3089. auto intend_to_store_in_bfcache = false;
  3090. // 6. Let eventLoop be oldDocument's relevant agent's event loop.
  3091. auto& event_loop = *verify_cast<Bindings::WebEngineCustomData>(*HTML::relevant_agent(*this).custom_data()).event_loop;
  3092. // 7. Increase eventLoop's termination nesting level by 1.
  3093. event_loop.increment_termination_nesting_level();
  3094. // 8. Increase oldDocument's unload counter by 1.
  3095. m_unload_counter += 1;
  3096. // 9. If intendToKeepInBfcache is false, then set oldDocument's salvageable state to false.
  3097. if (!intend_to_store_in_bfcache) {
  3098. m_salvageable = false;
  3099. }
  3100. // 10. If oldDocument's page showing is true:
  3101. if (m_page_showing) {
  3102. // 1. Set oldDocument's page showing to false.
  3103. m_page_showing = false;
  3104. // 2. Fire a page transition event named pagehide at oldDocument's relevant global object with oldDocument's salvageable state.
  3105. verify_cast<HTML::Window>(relevant_global_object(*this)).fire_a_page_transition_event(HTML::EventNames::pagehide, m_salvageable);
  3106. // 3. Update the visibility state of oldDocument to "hidden".
  3107. update_the_visibility_state(HTML::VisibilityState::Hidden);
  3108. }
  3109. // FIXME: 11. If unloadTimingInfo is not null, then set unloadTimingInfo's unload event start time to the current high resolution time given newDocument's relevant global object, coarsened
  3110. // given oldDocument's relevant settings object's cross-origin isolated capability.
  3111. // 12. If oldDocument's salvageable state is false, then fire an event named unload at oldDocument's relevant global object, with legacy target override flag set.
  3112. if (!m_salvageable) {
  3113. // then fire an event named unload at document's relevant global object, with legacy target override flag set.
  3114. // FIXME: The legacy target override flag is currently set by a virtual override of dispatch_event()
  3115. // We should reorganize this so that the flag appears explicitly here instead.
  3116. auto event = DOM::Event::create(realm(), HTML::EventNames::unload);
  3117. verify_cast<HTML::Window>(relevant_global_object(*this)).dispatch_event(event);
  3118. }
  3119. // FIXME: 13. If unloadTimingInfo is not null, then set unloadTimingInfo's unload event end time to the current high resolution time given newDocument's relevant global object, coarsened
  3120. // given oldDocument's relevant settings object's cross-origin isolated capability.
  3121. // 14. Decrease eventLoop's termination nesting level by 1.
  3122. event_loop.decrement_termination_nesting_level();
  3123. // FIXME: 15. Set oldDocument's suspension time to the current high resolution time given document's relevant global object.
  3124. // FIXME: 16. Set oldDocument's suspended timer handles to the result of getting the keys for the map of active timers.
  3125. // FIXME: 17. Set oldDocument's has been scrolled by the user to false.
  3126. // FIXME: 18. Run any unloading document cleanup steps for oldDocument that are defined by this specification and other applicable specifications.
  3127. // 19. If oldDocument's salvageable state is false, then destroy oldDocument.
  3128. if (!m_salvageable) {
  3129. // NOTE: Document is destroyed from Document::unload_a_document_and_its_descendants()
  3130. }
  3131. // 20. Decrease oldDocument's unload counter by 1.
  3132. m_unload_counter -= 1;
  3133. // FIXME: 21. If newDocument is given, newDocument's was created via cross-origin redirects is false, and newDocument's origin is the same as oldDocument's origin, then set
  3134. // newDocument's previous document unload timing to unloadTimingInfo.
  3135. did_stop_being_active_document_in_navigable();
  3136. }
  3137. // https://html.spec.whatwg.org/multipage/document-lifecycle.html#unload-a-document-and-its-descendants
  3138. void Document::unload_a_document_and_its_descendants(GC::Ptr<Document> new_document, GC::Ptr<GC::Function<void()>> after_all_unloads)
  3139. {
  3140. // Specification defines this algorithm in the following steps:
  3141. // 1. Recursively unload (and destroy) documents in descendant navigables
  3142. // 2. Unload (and destroy) this document.
  3143. //
  3144. // Implementation of the spec will fail in the following scenario:
  3145. // 1. Unload iframe's (has attribute name="test") document
  3146. // 1.1. Destroy iframe's document
  3147. // 2. Unload iframe's parent document
  3148. // 2.1. Dispatch "unload" event
  3149. // 2.2. In "unload" event handler run `window["test"]`
  3150. // 2.2.1. Execute Window::document_tree_child_navigable_target_name_property_set()
  3151. // 2.2.1.1. Fail to access iframe's navigable active document because it was destroyed on step 1.1
  3152. //
  3153. // We change the algorithm to:
  3154. // 1. Unload all descendant documents without destroying them
  3155. // 2. Unload this document
  3156. // 3. Destroy all descendant documents
  3157. // 4. Destroy this document
  3158. //
  3159. // This way we maintain the invariant that all navigable containers present in the DOM tree
  3160. // have an active document while the document is being unloaded.
  3161. IGNORE_USE_IN_ESCAPING_LAMBDA size_t number_unloaded = 0;
  3162. auto navigable = this->navigable();
  3163. Vector<GC::Root<HTML::Navigable>> descendant_navigables;
  3164. for (auto& other_navigable : HTML::all_navigables()) {
  3165. if (navigable->is_ancestor_of(*other_navigable))
  3166. descendant_navigables.append(other_navigable);
  3167. }
  3168. IGNORE_USE_IN_ESCAPING_LAMBDA auto unloaded_documents_count = descendant_navigables.size() + 1;
  3169. HTML::queue_global_task(HTML::Task::Source::NavigationAndTraversal, HTML::relevant_global_object(*this), GC::create_function(heap(), [&number_unloaded, this, new_document] {
  3170. unload(new_document);
  3171. ++number_unloaded;
  3172. }));
  3173. for (auto& descendant_navigable : descendant_navigables) {
  3174. HTML::queue_global_task(HTML::Task::Source::NavigationAndTraversal, *descendant_navigable->active_window(), GC::create_function(heap(), [&number_unloaded, descendant_navigable = descendant_navigable.ptr()] {
  3175. descendant_navigable->active_document()->unload();
  3176. ++number_unloaded;
  3177. }));
  3178. }
  3179. HTML::main_thread_event_loop().spin_until(GC::create_function(heap(), [&] {
  3180. return number_unloaded == unloaded_documents_count;
  3181. }));
  3182. destroy_a_document_and_its_descendants(move(after_all_unloads));
  3183. }
  3184. // https://html.spec.whatwg.org/multipage/iframe-embed-object.html#allowed-to-use
  3185. bool Document::is_allowed_to_use_feature(PolicyControlledFeature feature) const
  3186. {
  3187. // 1. If document's browsing context is null, then return false.
  3188. if (browsing_context() == nullptr)
  3189. return false;
  3190. // 2. If document is not fully active, then return false.
  3191. if (!is_fully_active())
  3192. return false;
  3193. // 3. If the result of running is feature enabled in document for origin on feature, document, and document's origin
  3194. // is "Enabled", then return true.
  3195. // FIXME: This is ad-hoc. Implement the Permissions Policy specification.
  3196. switch (feature) {
  3197. case PolicyControlledFeature::Autoplay:
  3198. if (PermissionsPolicy::AutoplayAllowlist::the().is_allowed_for_origin(*this, origin()) == PermissionsPolicy::Decision::Enabled)
  3199. return true;
  3200. break;
  3201. }
  3202. // 4. Return false.
  3203. return false;
  3204. }
  3205. void Document::did_stop_being_active_document_in_navigable()
  3206. {
  3207. tear_down_layout_tree();
  3208. notify_each_document_observer([&](auto const& document_observer) {
  3209. return document_observer.document_became_inactive();
  3210. });
  3211. if (m_animation_driver_timer)
  3212. m_animation_driver_timer->stop();
  3213. }
  3214. void Document::increment_throw_on_dynamic_markup_insertion_counter(Badge<HTML::HTMLParser>)
  3215. {
  3216. ++m_throw_on_dynamic_markup_insertion_counter;
  3217. }
  3218. void Document::decrement_throw_on_dynamic_markup_insertion_counter(Badge<HTML::HTMLParser>)
  3219. {
  3220. VERIFY(m_throw_on_dynamic_markup_insertion_counter);
  3221. --m_throw_on_dynamic_markup_insertion_counter;
  3222. }
  3223. // https://html.spec.whatwg.org/multipage/scripting.html#appropriate-template-contents-owner-document
  3224. GC::Ref<DOM::Document> Document::appropriate_template_contents_owner_document()
  3225. {
  3226. // 1. If doc is not a Document created by this algorithm, then:
  3227. if (!created_for_appropriate_template_contents()) {
  3228. // 1. If doc does not yet have an associated inert template document, then:
  3229. if (!m_associated_inert_template_document) {
  3230. // 1. Let new doc be a new Document (whose browsing context is null). This is "a Document created by this algorithm" for the purposes of the step above.
  3231. auto new_document = HTML::HTMLDocument::create(realm());
  3232. new_document->m_created_for_appropriate_template_contents = true;
  3233. // 2. If doc is an HTML document, mark new doc as an HTML document also.
  3234. if (document_type() == Type::HTML)
  3235. new_document->set_document_type(Type::HTML);
  3236. // 3. Let doc's associated inert template document be new doc.
  3237. m_associated_inert_template_document = new_document;
  3238. }
  3239. // 2. Set doc to doc's associated inert template document.
  3240. return *m_associated_inert_template_document;
  3241. }
  3242. // 2. Return doc.
  3243. return *this;
  3244. }
  3245. String Document::dump_accessibility_tree_as_json()
  3246. {
  3247. StringBuilder builder;
  3248. auto accessibility_tree = AccessibilityTreeNode::create(this, nullptr);
  3249. build_accessibility_tree(*&accessibility_tree);
  3250. auto json = MUST(JsonObjectSerializer<>::try_create(builder));
  3251. // Empty document
  3252. if (!accessibility_tree->value()) {
  3253. MUST(json.add("type"sv, "element"sv));
  3254. MUST(json.add("role"sv, "document"sv));
  3255. } else {
  3256. accessibility_tree->serialize_tree_as_json(json, *this);
  3257. }
  3258. MUST(json.finish());
  3259. return MUST(builder.to_string());
  3260. }
  3261. // https://dom.spec.whatwg.org/#dom-document-createattribute
  3262. WebIDL::ExceptionOr<GC::Ref<Attr>> Document::create_attribute(String const& local_name)
  3263. {
  3264. // 1. If localName does not match the Name production in XML, then throw an "InvalidCharacterError" DOMException.
  3265. if (!is_valid_name(local_name))
  3266. return WebIDL::InvalidCharacterError::create(realm(), "Invalid character in attribute name."_string);
  3267. // 2. If this is an HTML document, then set localName to localName in ASCII lowercase.
  3268. // 3. Return a new attribute whose local name is localName and node document is this.
  3269. return Attr::create(*this, is_html_document() ? local_name.to_ascii_lowercase() : local_name);
  3270. }
  3271. // https://dom.spec.whatwg.org/#dom-document-createattributens
  3272. WebIDL::ExceptionOr<GC::Ref<Attr>> Document::create_attribute_ns(Optional<FlyString> const& namespace_, String const& qualified_name)
  3273. {
  3274. // 1. Let namespace, prefix, and localName be the result of passing namespace and qualifiedName to validate and extract.
  3275. auto extracted_qualified_name = TRY(validate_and_extract(realm(), namespace_, qualified_name));
  3276. // 2. Return a new attribute whose namespace is namespace, namespace prefix is prefix, local name is localName, and node document is this.
  3277. return Attr::create(*this, extracted_qualified_name);
  3278. }
  3279. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#make-active
  3280. void Document::make_active()
  3281. {
  3282. // 1. Let window be document's relevant global object.
  3283. auto& window = verify_cast<HTML::Window>(HTML::relevant_global_object(*this));
  3284. set_window(window);
  3285. // 2. Set document's browsing context's WindowProxy's [[Window]] internal slot value to window.
  3286. m_browsing_context->window_proxy()->set_window(window);
  3287. if (m_browsing_context->is_top_level()) {
  3288. page().client().page_did_change_active_document_in_top_level_browsing_context(*this);
  3289. }
  3290. // 3. Set document's visibility state to document's node navigable's traversable navigable's system visibility state.
  3291. if (navigable()) {
  3292. m_visibility_state = navigable()->traversable_navigable()->system_visibility_state();
  3293. }
  3294. // TODO: 4. Queue a new VisibilityStateEntry whose visibility state is document's visibility state and whose timestamp is zero.
  3295. // 5. Set window's relevant settings object's execution ready flag.
  3296. HTML::relevant_settings_object(window).execution_ready = true;
  3297. if (m_needs_to_call_page_did_load) {
  3298. navigable()->traversable_navigable()->page().client().page_did_finish_loading(url());
  3299. m_needs_to_call_page_did_load = false;
  3300. }
  3301. notify_each_document_observer([&](auto const& document_observer) {
  3302. return document_observer.document_became_active();
  3303. });
  3304. }
  3305. HTML::ListOfAvailableImages& Document::list_of_available_images()
  3306. {
  3307. return *m_list_of_available_images;
  3308. }
  3309. HTML::ListOfAvailableImages const& Document::list_of_available_images() const
  3310. {
  3311. return *m_list_of_available_images;
  3312. }
  3313. CSSPixelRect Document::viewport_rect() const
  3314. {
  3315. if (auto const navigable = this->navigable())
  3316. return navigable->viewport_rect();
  3317. return CSSPixelRect {};
  3318. }
  3319. GC::Ref<CSS::VisualViewport> Document::visual_viewport()
  3320. {
  3321. if (!m_visual_viewport)
  3322. m_visual_viewport = CSS::VisualViewport::create(*this);
  3323. return *m_visual_viewport;
  3324. }
  3325. void Document::register_viewport_client(ViewportClient& client)
  3326. {
  3327. auto result = m_viewport_clients.set(&client);
  3328. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  3329. }
  3330. void Document::unregister_viewport_client(ViewportClient& client)
  3331. {
  3332. bool was_removed = m_viewport_clients.remove(&client);
  3333. VERIFY(was_removed);
  3334. }
  3335. void Document::inform_all_viewport_clients_about_the_current_viewport_rect()
  3336. {
  3337. for (auto* client : m_viewport_clients)
  3338. client->did_set_viewport_rect(viewport_rect());
  3339. }
  3340. void Document::register_intersection_observer(Badge<IntersectionObserver::IntersectionObserver>, IntersectionObserver::IntersectionObserver& observer)
  3341. {
  3342. auto result = m_intersection_observers.set(observer);
  3343. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  3344. }
  3345. void Document::unregister_intersection_observer(Badge<IntersectionObserver::IntersectionObserver>, IntersectionObserver::IntersectionObserver& observer)
  3346. {
  3347. bool was_removed = m_intersection_observers.remove(observer);
  3348. VERIFY(was_removed);
  3349. }
  3350. void Document::register_resize_observer(Badge<ResizeObserver::ResizeObserver>, ResizeObserver::ResizeObserver& observer)
  3351. {
  3352. m_resize_observers.append(observer);
  3353. }
  3354. void Document::unregister_resize_observer(Badge<ResizeObserver::ResizeObserver>, ResizeObserver::ResizeObserver& observer)
  3355. {
  3356. m_resize_observers.remove_first_matching([&](auto& registered_observer) {
  3357. return registered_observer.ptr() == &observer;
  3358. });
  3359. }
  3360. // https://www.w3.org/TR/intersection-observer/#queue-an-intersection-observer-task
  3361. void Document::queue_intersection_observer_task()
  3362. {
  3363. auto window = this->window();
  3364. if (!window)
  3365. return;
  3366. // 1. If document’s IntersectionObserverTaskQueued flag is set to true, return.
  3367. if (m_intersection_observer_task_queued)
  3368. return;
  3369. // 2. Set document’s IntersectionObserverTaskQueued flag to true.
  3370. m_intersection_observer_task_queued = true;
  3371. // 3. Queue a task on the IntersectionObserver task source associated with the document's event loop to notify intersection observers.
  3372. HTML::queue_global_task(HTML::Task::Source::IntersectionObserver, *window, GC::create_function(heap(), [this]() {
  3373. auto& realm = this->realm();
  3374. // https://www.w3.org/TR/intersection-observer/#notify-intersection-observers
  3375. // 1. Set document’s IntersectionObserverTaskQueued flag to false.
  3376. m_intersection_observer_task_queued = false;
  3377. // 2. Let notify list be a list of all IntersectionObservers whose root is in the DOM tree of document.
  3378. Vector<GC::Root<IntersectionObserver::IntersectionObserver>> notify_list;
  3379. notify_list.try_ensure_capacity(m_intersection_observers.size()).release_value_but_fixme_should_propagate_errors();
  3380. for (auto& observer : m_intersection_observers) {
  3381. notify_list.append(GC::make_root(observer));
  3382. }
  3383. // 3. For each IntersectionObserver object observer in notify list, run these steps:
  3384. for (auto& observer : notify_list) {
  3385. // 2. Let queue be a copy of observer’s internal [[QueuedEntries]] slot.
  3386. // 3. Clear observer’s internal [[QueuedEntries]] slot.
  3387. auto queue = observer->take_records();
  3388. // 1. If observer’s internal [[QueuedEntries]] slot is empty, continue.
  3389. if (queue.is_empty())
  3390. continue;
  3391. auto wrapped_queue = MUST(JS::Array::create(realm, 0));
  3392. for (size_t i = 0; i < queue.size(); ++i) {
  3393. auto& record = queue.at(i);
  3394. auto property_index = JS::PropertyKey { i };
  3395. MUST(wrapped_queue->create_data_property(property_index, record.ptr()));
  3396. }
  3397. // 4. Let callback be the value of observer’s internal [[callback]] slot.
  3398. auto& callback = observer->callback();
  3399. // 5. Invoke callback with queue as the first argument, observer as the second argument, and observer as the callback this value. If this throws an exception, report the exception.
  3400. // NOTE: This does not follow the spec as written precisely, but this is the same thing we do elsewhere and there is a WPT test that relies on this.
  3401. (void)WebIDL::invoke_callback(callback, observer.ptr(), WebIDL::ExceptionBehavior::Report, wrapped_queue, observer.ptr());
  3402. }
  3403. }));
  3404. }
  3405. // https://www.w3.org/TR/intersection-observer/#queue-an-intersectionobserverentry
  3406. void Document::queue_an_intersection_observer_entry(IntersectionObserver::IntersectionObserver& observer, HighResolutionTime::DOMHighResTimeStamp time, GC::Ref<Geometry::DOMRectReadOnly> root_bounds, GC::Ref<Geometry::DOMRectReadOnly> bounding_client_rect, GC::Ref<Geometry::DOMRectReadOnly> intersection_rect, bool is_intersecting, double intersection_ratio, GC::Ref<Element> target)
  3407. {
  3408. auto& realm = this->realm();
  3409. // 1. Construct an IntersectionObserverEntry, passing in time, rootBounds, boundingClientRect, intersectionRect, isIntersecting, and target.
  3410. auto entry = realm.create<IntersectionObserver::IntersectionObserverEntry>(realm, time, root_bounds, bounding_client_rect, intersection_rect, is_intersecting, intersection_ratio, target);
  3411. // 2. Append it to observer’s internal [[QueuedEntries]] slot.
  3412. observer.queue_entry({}, entry);
  3413. // 3. Queue an intersection observer task for document.
  3414. queue_intersection_observer_task();
  3415. }
  3416. // https://www.w3.org/TR/intersection-observer/#compute-the-intersection
  3417. static GC::Ref<Geometry::DOMRectReadOnly> compute_intersection(GC::Ref<Element> target, IntersectionObserver::IntersectionObserver const& observer)
  3418. {
  3419. // 1. Let intersectionRect be the result of getting the bounding box for target.
  3420. auto intersection_rect = target->get_bounding_client_rect();
  3421. // FIXME: 2. Let container be the containing block of target.
  3422. // FIXME: 3. While container is not root:
  3423. // FIXME: 1. If container is the document of a nested browsing context, update intersectionRect by clipping to
  3424. // the viewport of the document, and update container to be the browsing context container of container.
  3425. // FIXME: 2. Map intersectionRect to the coordinate space of container.
  3426. // FIXME: 3. If container has a content clip or a css clip-path property, update intersectionRect by applying
  3427. // container’s clip.
  3428. // FIXME: 4. If container is the root element of a browsing context, update container to be the browsing context’s
  3429. // document; otherwise, update container to be the containing block of container.
  3430. // FIXME: 4. Map intersectionRect to the coordinate space of root.
  3431. // 5. Update intersectionRect by intersecting it with the root intersection rectangle.
  3432. // FIXME: Pass in target so we can properly apply rootMargin.
  3433. auto root_intersection_rectangle = observer.root_intersection_rectangle();
  3434. CSSPixelRect intersection_rect_as_pixel_rect(intersection_rect->x(), intersection_rect->y(), intersection_rect->width(), intersection_rect->height());
  3435. intersection_rect_as_pixel_rect.intersect(root_intersection_rectangle);
  3436. intersection_rect->set_x(static_cast<double>(intersection_rect_as_pixel_rect.x()));
  3437. intersection_rect->set_y(static_cast<double>(intersection_rect_as_pixel_rect.y()));
  3438. intersection_rect->set_width(static_cast<double>(intersection_rect_as_pixel_rect.width()));
  3439. intersection_rect->set_height(static_cast<double>(intersection_rect_as_pixel_rect.height()));
  3440. // FIXME: 6. Map intersectionRect to the coordinate space of the viewport of the document containing target.
  3441. // 7. Return intersectionRect.
  3442. return intersection_rect;
  3443. }
  3444. // https://www.w3.org/TR/intersection-observer/#run-the-update-intersection-observations-steps
  3445. void Document::run_the_update_intersection_observations_steps(HighResolutionTime::DOMHighResTimeStamp time)
  3446. {
  3447. auto& realm = this->realm();
  3448. // 1. Let observer list be a list of all IntersectionObservers whose root is in the DOM tree of document.
  3449. // For the top-level browsing context, this includes implicit root observers.
  3450. // 2. For each observer in observer list:
  3451. // NOTE: We make a copy of the intersection observers list to avoid modifying it while iterating.
  3452. GC::RootVector<GC::Ref<IntersectionObserver::IntersectionObserver>> intersection_observers(heap());
  3453. intersection_observers.ensure_capacity(m_intersection_observers.size());
  3454. for (auto& observer : m_intersection_observers)
  3455. intersection_observers.append(observer);
  3456. for (auto& observer : intersection_observers) {
  3457. // 1. Let rootBounds be observer’s root intersection rectangle.
  3458. auto root_bounds = observer->root_intersection_rectangle();
  3459. // 2. For each target in observer’s internal [[ObservationTargets]] slot, processed in the same order that
  3460. // observe() was called on each target:
  3461. for (auto& target : observer->observation_targets()) {
  3462. // 1. Let:
  3463. // thresholdIndex be 0.
  3464. size_t threshold_index = 0;
  3465. // isIntersecting be false.
  3466. bool is_intersecting = false;
  3467. // targetRect be a DOMRectReadOnly with x, y, width, and height set to 0.
  3468. auto target_rect = Geometry::DOMRectReadOnly::construct_impl(realm, 0, 0, 0, 0).release_value_but_fixme_should_propagate_errors();
  3469. // intersectionRect be a DOMRectReadOnly with x, y, width, and height set to 0.
  3470. auto intersection_rect = Geometry::DOMRectReadOnly::construct_impl(realm, 0, 0, 0, 0).release_value_but_fixme_should_propagate_errors();
  3471. // SPEC ISSUE: It doesn't pass in intersection ratio to "queue an IntersectionObserverEntry" despite needing it.
  3472. // This is default 0, as isIntersecting is default false, see step 9.
  3473. double intersection_ratio = 0.0;
  3474. // 2. If the intersection root is not the implicit root, and target is not in the same document as the intersection root, skip to step 11.
  3475. // 3. If the intersection root is an Element, and target is not a descendant of the intersection root in the containing block chain, skip to step 11.
  3476. // FIXME: Actually use the containing block chain.
  3477. auto intersection_root = observer->intersection_root();
  3478. auto intersection_root_document = intersection_root.visit([](auto& node) -> GC::Ref<Document> {
  3479. return node->document();
  3480. });
  3481. if (!(observer->root().has<Empty>() && &target->document() == intersection_root_document.ptr())
  3482. || !(intersection_root.has<GC::Root<DOM::Element>>() && !target->is_descendant_of(*intersection_root.get<GC::Root<DOM::Element>>()))) {
  3483. // 4. Set targetRect to the DOMRectReadOnly obtained by getting the bounding box for target.
  3484. target_rect = target->get_bounding_client_rect();
  3485. // 5. Let intersectionRect be the result of running the compute the intersection algorithm on target and
  3486. // observer’s intersection root.
  3487. intersection_rect = compute_intersection(target, observer);
  3488. // 6. Let targetArea be targetRect’s area.
  3489. auto target_area = target_rect->width() * target_rect->height();
  3490. // 7. Let intersectionArea be intersectionRect’s area.
  3491. auto intersection_area = intersection_rect->width() * intersection_rect->height();
  3492. // 8. Let isIntersecting be true if targetRect and rootBounds intersect or are edge-adjacent, even if the
  3493. // intersection has zero area (because rootBounds or targetRect have zero area).
  3494. CSSPixelRect target_rect_as_pixel_rect(target_rect->x(), target_rect->y(), target_rect->width(), target_rect->height());
  3495. is_intersecting = target_rect_as_pixel_rect.intersects(root_bounds);
  3496. // 9. If targetArea is non-zero, let intersectionRatio be intersectionArea divided by targetArea.
  3497. // Otherwise, let intersectionRatio be 1 if isIntersecting is true, or 0 if isIntersecting is false.
  3498. if (target_area != 0.0)
  3499. intersection_ratio = intersection_area / target_area;
  3500. else
  3501. intersection_ratio = is_intersecting ? 1.0 : 0.0;
  3502. // 10. Set thresholdIndex to the index of the first entry in observer.thresholds whose value is greater
  3503. // than intersectionRatio, or the length of observer.thresholds if intersectionRatio is greater than
  3504. // or equal to the last entry in observer.thresholds.
  3505. threshold_index = observer->thresholds().find_first_index_if([&intersection_ratio](double threshold_value) {
  3506. return threshold_value > intersection_ratio;
  3507. })
  3508. .value_or(observer->thresholds().size());
  3509. }
  3510. // 11. Let intersectionObserverRegistration be the IntersectionObserverRegistration record in target’s
  3511. // internal [[RegisteredIntersectionObservers]] slot whose observer property is equal to observer.
  3512. auto& intersection_observer_registration = target->get_intersection_observer_registration({}, observer);
  3513. // 12. Let previousThresholdIndex be the intersectionObserverRegistration’s previousThresholdIndex property.
  3514. auto previous_threshold_index = intersection_observer_registration.previous_threshold_index;
  3515. // 13. Let previousIsIntersecting be the intersectionObserverRegistration’s previousIsIntersecting property.
  3516. auto previous_is_intersecting = intersection_observer_registration.previous_is_intersecting;
  3517. // 14. If thresholdIndex does not equal previousThresholdIndex or if isIntersecting does not equal
  3518. // previousIsIntersecting, queue an IntersectionObserverEntry, passing in observer, time,
  3519. // rootBounds, targetRect, intersectionRect, isIntersecting, and target.
  3520. if (threshold_index != previous_threshold_index || is_intersecting != previous_is_intersecting) {
  3521. auto root_bounds_as_dom_rect = Geometry::DOMRectReadOnly::construct_impl(realm, static_cast<double>(root_bounds.x()), static_cast<double>(root_bounds.y()), static_cast<double>(root_bounds.width()), static_cast<double>(root_bounds.height())).release_value_but_fixme_should_propagate_errors();
  3522. // SPEC ISSUE: It doesn't pass in intersectionRatio, but it's required.
  3523. queue_an_intersection_observer_entry(observer, time, root_bounds_as_dom_rect, target_rect, intersection_rect, is_intersecting, intersection_ratio, target);
  3524. }
  3525. // 15. Assign thresholdIndex to intersectionObserverRegistration’s previousThresholdIndex property.
  3526. intersection_observer_registration.previous_threshold_index = threshold_index;
  3527. // 16. Assign isIntersecting to intersectionObserverRegistration’s previousIsIntersecting property.
  3528. intersection_observer_registration.previous_is_intersecting = is_intersecting;
  3529. }
  3530. }
  3531. }
  3532. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#start-intersection-observing-a-lazy-loading-element
  3533. void Document::start_intersection_observing_a_lazy_loading_element(Element& element)
  3534. {
  3535. VERIFY(element.is_lazy_loading());
  3536. auto& realm = this->realm();
  3537. // 1. Let doc be element's node document.
  3538. VERIFY(&element.document() == this);
  3539. // 2. If doc's lazy load intersection observer is null, set it to a new IntersectionObserver instance, initialized as follows:
  3540. if (!m_lazy_load_intersection_observer) {
  3541. // - The callback is these steps, with arguments entries and observer:
  3542. auto callback = JS::NativeFunction::create(realm, "", [this](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
  3543. // For each entry in entries using a method of iteration which does not trigger developer-modifiable array accessors or iteration hooks:
  3544. auto& entries = verify_cast<JS::Array>(vm.argument(0).as_object());
  3545. auto entries_length = MUST(MUST(entries.get(vm.names.length)).to_length(vm));
  3546. for (size_t i = 0; i < entries_length; ++i) {
  3547. auto property_key = JS::PropertyKey { i };
  3548. auto& entry = verify_cast<IntersectionObserver::IntersectionObserverEntry>(entries.get_without_side_effects(property_key).as_object());
  3549. // 1. Let resumptionSteps be null.
  3550. GC::Ptr<GC::Function<void()>> resumption_steps;
  3551. // 2. If entry.isIntersecting is true, then set resumptionSteps to entry.target's lazy load resumption steps.
  3552. if (entry.is_intersecting()) {
  3553. // 5. Set entry.target's lazy load resumption steps to null.
  3554. VERIFY(entry.target()->is_lazy_loading());
  3555. resumption_steps = entry.target()->take_lazy_load_resumption_steps({});
  3556. }
  3557. // 3. If resumptionSteps is null, then return.
  3558. if (!resumption_steps) {
  3559. // NOTE: This is wrong in the spec, since we want to keep processing
  3560. // entries even if one of them doesn't have resumption steps.
  3561. // FIXME: Spec bug: https://github.com/whatwg/html/issues/10019
  3562. continue;
  3563. }
  3564. // 4. Stop intersection-observing a lazy loading element for entry.target.
  3565. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#stop-intersection-observing-a-lazy-loading-element
  3566. // 1. Let doc be element's node document.
  3567. // NOTE: It's `this`.
  3568. // 2. Assert: doc's lazy load intersection observer is not null.
  3569. VERIFY(m_lazy_load_intersection_observer);
  3570. // 3. Call doc's lazy load intersection observer unobserve method with element as the argument.
  3571. m_lazy_load_intersection_observer->unobserve(entry.target());
  3572. // 6. Invoke resumptionSteps.
  3573. resumption_steps->function()();
  3574. }
  3575. return JS::js_undefined();
  3576. });
  3577. // FIXME: The options is an IntersectionObserverInit dictionary with the following dictionary members: «[ "rootMargin" → lazy load root margin ]»
  3578. // Spec Note: This allows for fetching the image during scrolling, when it does not yet — but is about to — intersect the viewport.
  3579. auto options = IntersectionObserver::IntersectionObserverInit {};
  3580. auto wrapped_callback = realm.heap().allocate<WebIDL::CallbackType>(callback, realm);
  3581. m_lazy_load_intersection_observer = IntersectionObserver::IntersectionObserver::construct_impl(realm, wrapped_callback, options).release_value_but_fixme_should_propagate_errors();
  3582. }
  3583. // 3. Call doc's lazy load intersection observer's observe method with element as the argument.
  3584. VERIFY(m_lazy_load_intersection_observer);
  3585. m_lazy_load_intersection_observer->observe(element);
  3586. }
  3587. // https://html.spec.whatwg.org/multipage/semantics.html#shared-declarative-refresh-steps
  3588. void Document::shared_declarative_refresh_steps(StringView input, GC::Ptr<HTML::HTMLMetaElement const> meta_element)
  3589. {
  3590. // 1. If document's will declaratively refresh is true, then return.
  3591. if (m_will_declaratively_refresh)
  3592. return;
  3593. // 2. Let position point at the first code point of input.
  3594. GenericLexer lexer(input);
  3595. // 3. Skip ASCII whitespace within input given position.
  3596. lexer.ignore_while(Infra::is_ascii_whitespace);
  3597. // 4. Let time be 0.
  3598. u32 time = 0;
  3599. // 5. Collect a sequence of code points that are ASCII digits from input given position, and let the result be timeString.
  3600. auto time_string = lexer.consume_while(is_ascii_digit);
  3601. // 6. If timeString is the empty string, then:
  3602. if (time_string.is_empty()) {
  3603. // 1. If the code point in input pointed to by position is not U+002E (.), then return.
  3604. if (lexer.peek() != '.')
  3605. return;
  3606. }
  3607. // 7. Otherwise, set time to the result of parsing timeString using the rules for parsing non-negative integers.
  3608. auto maybe_time = Web::HTML::parse_non_negative_integer(time_string);
  3609. // FIXME: Since we only collected ASCII digits, this can only fail because of overflow. What do we do when that happens? For now, default to 0.
  3610. if (maybe_time.has_value() && maybe_time.value() < NumericLimits<int>::max() && !Checked<int>::multiplication_would_overflow(static_cast<int>(maybe_time.value()), 1000)) {
  3611. time = maybe_time.value();
  3612. }
  3613. // 8. Collect a sequence of code points that are ASCII digits and U+002E FULL STOP characters (.) from input given
  3614. // position. Ignore any collected characters.
  3615. lexer.ignore_while([](auto c) {
  3616. return is_ascii_digit(c) || c == '.';
  3617. });
  3618. // 9. Let urlRecord be document's URL.
  3619. auto url_record = url();
  3620. // 10. If position is not past the end of input, then:
  3621. if (!lexer.is_eof()) {
  3622. // 1. If the code point in input pointed to by position is not U+003B (;), U+002C (,), or ASCII whitespace, then return.
  3623. if (lexer.peek() != ';' && lexer.peek() != ',' && !Infra::is_ascii_whitespace(lexer.peek()))
  3624. return;
  3625. // 2. Skip ASCII whitespace within input given position.
  3626. lexer.ignore_while(Infra::is_ascii_whitespace);
  3627. // 3. If the code point in input pointed to by position is U+003B (;) or U+002C (,), then advance position to the next code point.
  3628. if (lexer.peek() == ';' || lexer.peek() == ',')
  3629. lexer.ignore(1);
  3630. // 4. Skip ASCII whitespace within input given position.
  3631. lexer.ignore_while(Infra::is_ascii_whitespace);
  3632. }
  3633. // 11. If position is not past the end of input, then:
  3634. if (!lexer.is_eof()) {
  3635. // 1. Let urlString be the substring of input from the code point at position to the end of the string.
  3636. auto url_string = lexer.remaining();
  3637. // 2. If the code point in input pointed to by position is U+0055 (U) or U+0075 (u), then advance position to the next code point. Otherwise, jump to the step labeled skip quotes.
  3638. if (lexer.peek() == 'U' || lexer.peek() == 'u')
  3639. lexer.ignore(1);
  3640. else
  3641. goto skip_quotes;
  3642. // 3. If the code point in input pointed to by position is U+0052 (R) or U+0072 (r), then advance position to the next code point. Otherwise, jump to the step labeled parse.
  3643. if (lexer.peek() == 'R' || lexer.peek() == 'r')
  3644. lexer.ignore(1);
  3645. else
  3646. goto parse;
  3647. // 4. If the code point in input pointed to by position is U+004C (L) or U+006C (l), then advance position to the next code point. Otherwise, jump to the step labeled parse.
  3648. if (lexer.peek() == 'L' || lexer.peek() == 'l')
  3649. lexer.ignore(1);
  3650. else
  3651. goto parse;
  3652. // 5. Skip ASCII whitespace within input given position.
  3653. lexer.ignore_while(Infra::is_ascii_whitespace);
  3654. // 6. If the code point in input pointed to by position is U+003D (=), then advance position to the next code point. Otherwise, jump to the step labeled parse.
  3655. if (lexer.peek() == '=')
  3656. lexer.ignore(1);
  3657. else
  3658. goto parse;
  3659. // 7. Skip ASCII whitespace within input given position.
  3660. lexer.ignore_while(Infra::is_ascii_whitespace);
  3661. skip_quotes: {
  3662. // 8. Skip quotes: If the code point in input pointed to by position is U+0027 (') or U+0022 ("), then let
  3663. // quote be that code point, and advance position to the next code point. Otherwise, let quote be the empty
  3664. // string.
  3665. Optional<char> quote;
  3666. if (lexer.peek() == '\'' || lexer.peek() == '"')
  3667. quote = lexer.consume();
  3668. // 9. Set urlString to the substring of input from the code point at position to the end of the string.
  3669. // 10. If quote is not the empty string, and there is a code point in urlString equal to quote, then truncate
  3670. // urlString at that code point, so that it and all subsequent code points are removed.
  3671. url_string = lexer.consume_while([&quote](auto c) {
  3672. return !quote.has_value() || c != quote.value();
  3673. });
  3674. }
  3675. parse:
  3676. // 11. Parse: Parse urlString relative to document. If that fails, return. Otherwise, set urlRecord to the
  3677. // resulting URL record.
  3678. auto maybe_url_record = parse_url(url_string);
  3679. if (!maybe_url_record.is_valid())
  3680. return;
  3681. url_record = maybe_url_record;
  3682. }
  3683. // 12. Set document's will declaratively refresh to true.
  3684. m_will_declaratively_refresh = true;
  3685. // 13. Perform one or more of the following steps:
  3686. // - After the refresh has come due (as defined below), if the user has not canceled the redirect and, if meta is
  3687. // given, document's active sandboxing flag set does not have the sandboxed automatic features browsing context
  3688. // flag set, then navigate document's node navigable to urlRecord using document, with historyHandling set to
  3689. // "replace".
  3690. m_active_refresh_timer = Core::Timer::create_single_shot(time * 1000, [this, has_meta_element = !!meta_element, url_record = move(url_record)]() {
  3691. if (has_meta_element && has_flag(active_sandboxing_flag_set(), HTML::SandboxingFlagSet::SandboxedAutomaticFeatures))
  3692. return;
  3693. auto navigable = this->navigable();
  3694. if (!navigable || navigable->has_been_destroyed())
  3695. return;
  3696. MUST(navigable->navigate({ .url = url_record, .source_document = *this, .history_handling = Bindings::NavigationHistoryBehavior::Replace }));
  3697. });
  3698. // For the purposes of the previous paragraph, a refresh is said to have come due as soon as the later of the
  3699. // following two conditions occurs:
  3700. // - At least time seconds have elapsed since document's completely loaded time, adjusted to take into
  3701. // account user or user agent preferences.
  3702. // m_active_refresh_timer is started in completely_finished_loading after setting the completely loaded time.
  3703. // - If meta is given, at least time seconds have elapsed since meta was inserted into the document document,
  3704. // adjusted to take into account user or user agent preferences.
  3705. // NOTE: This is only done if completely loaded time has a value because shared_declarative_refresh_steps is called
  3706. // by HTMLMetaElement::inserted and if the document hasn't finished loading when the meta element was inserted,
  3707. // then the document completely finishing loading will _always_ come after inserting the meta element.
  3708. if (meta_element && m_completely_loaded_time.has_value()) {
  3709. m_active_refresh_timer->start();
  3710. }
  3711. }
  3712. Painting::ViewportPaintable const* Document::paintable() const
  3713. {
  3714. return static_cast<Painting::ViewportPaintable const*>(Node::paintable());
  3715. }
  3716. Painting::ViewportPaintable* Document::paintable()
  3717. {
  3718. return static_cast<Painting::ViewportPaintable*>(Node::paintable());
  3719. }
  3720. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#restore-the-history-object-state
  3721. void Document::restore_the_history_object_state(GC::Ref<HTML::SessionHistoryEntry> entry)
  3722. {
  3723. // 1. Let targetRealm be document's relevant realm.
  3724. auto& target_realm = HTML::relevant_realm(*this);
  3725. // 2. Let state be StructuredDeserialize(entry's classic history API state, targetRealm). If this throws an exception, catch it and let state be null.
  3726. // 3. Set document's history object's state to state.
  3727. auto state_or_error = HTML::structured_deserialize(target_realm.vm(), entry->classic_history_api_state(), target_realm);
  3728. if (state_or_error.is_error())
  3729. m_history->set_state(JS::js_null());
  3730. else
  3731. m_history->set_state(state_or_error.release_value());
  3732. }
  3733. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#update-document-for-history-step-application
  3734. void Document::update_for_history_step_application(GC::Ref<HTML::SessionHistoryEntry> entry, bool do_not_reactivate, size_t script_history_length, size_t script_history_index, Optional<Bindings::NavigationType> navigation_type, Optional<Vector<GC::Ref<HTML::SessionHistoryEntry>>> entries_for_navigation_api, GC::Ptr<HTML::SessionHistoryEntry> previous_entry_for_activation, bool update_navigation_api)
  3735. {
  3736. (void)previous_entry_for_activation;
  3737. // 1. Let documentIsNew be true if document's latest entry is null; otherwise false.
  3738. auto document_is_new = !m_latest_entry;
  3739. // 2. Let documentsEntryChanged be true if document's latest entry is not entry; otherwise false.
  3740. auto documents_entry_changed = m_latest_entry != entry;
  3741. // 3. Set document's history object's index to scriptHistoryIndex.
  3742. history()->m_index = script_history_index;
  3743. // 4. Set document's history object's length to scriptHistoryLength.
  3744. history()->m_length = script_history_length;
  3745. // 5. Let navigation be history's relevant global object's navigation API.
  3746. auto navigation = verify_cast<HTML::Window>(HTML::relevant_global_object(*this)).navigation();
  3747. // 6. If documentsEntryChanged is true, then:
  3748. // NOTE: documentsEntryChanged can be false for one of two reasons: either we are restoring from bfcache,
  3749. // or we are asynchronously finishing up a synchronous navigation which already synchronously set document's latest entry.
  3750. // The doNotReactivate argument distinguishes between these two cases.
  3751. if (documents_entry_changed) {
  3752. // 1. Let oldURL be document's latest entry's URL.
  3753. auto old_url = m_latest_entry ? m_latest_entry->url() : URL::URL {};
  3754. // 2. Set document's latest entry to entry.
  3755. m_latest_entry = entry;
  3756. // 3. Restore the history object state given document and entry.
  3757. restore_the_history_object_state(entry);
  3758. // 4. If documentIsNew is false, then:
  3759. if (!document_is_new) {
  3760. // NOTE: Not in the spec, but otherwise document's url won't be updated in case of a same-document back/forward navigation.
  3761. set_url(entry->url());
  3762. // 1. Assert: navigationType is not null.
  3763. VERIFY(navigation_type.has_value());
  3764. // AD HOC: Skip this in situations the spec steps don't account for
  3765. if (update_navigation_api) {
  3766. // 2. Update the navigation API entries for a same-document navigation given navigation, entry, and navigationType.
  3767. navigation->update_the_navigation_api_entries_for_a_same_document_navigation(entry, navigation_type.value());
  3768. }
  3769. // 3. Fire an event named popstate at document's relevant global object, using PopStateEvent,
  3770. // with the state attribute initialized to document's history object's state and hasUAVisualTransition initialized to true
  3771. // if a visual transition, to display a cached rendered state of the latest entry, was done by the user agent.
  3772. // FIXME: Initialise hasUAVisualTransition
  3773. HTML::PopStateEventInit popstate_event_init;
  3774. popstate_event_init.state = history()->unsafe_state();
  3775. auto& relevant_global_object = verify_cast<HTML::Window>(HTML::relevant_global_object(*this));
  3776. auto pop_state_event = HTML::PopStateEvent::create(realm(), "popstate"_fly_string, popstate_event_init);
  3777. relevant_global_object.dispatch_event(pop_state_event);
  3778. // FIXME: 4. Restore persisted state given entry.
  3779. // 5. If oldURL's fragment is not equal to entry's URL's fragment, then queue a global task on the DOM manipulation task source
  3780. // given document's relevant global object to fire an event named hashchange at document's relevant global object,
  3781. // using HashChangeEvent, with the oldURL attribute initialized to the serialization of oldURL and the newURL attribute
  3782. // initialized to the serialization of entry's URL.
  3783. if (old_url.fragment() != entry->url().fragment()) {
  3784. HTML::HashChangeEventInit hashchange_event_init;
  3785. hashchange_event_init.old_url = old_url.serialize();
  3786. hashchange_event_init.new_url = entry->url().serialize();
  3787. auto hashchange_event = HTML::HashChangeEvent::create(realm(), "hashchange"_fly_string, hashchange_event_init);
  3788. HTML::queue_global_task(HTML::Task::Source::DOMManipulation, relevant_global_object, GC::create_function(heap(), [hashchange_event, &relevant_global_object]() {
  3789. relevant_global_object.dispatch_event(hashchange_event);
  3790. }));
  3791. }
  3792. }
  3793. // 5. Otherwise:
  3794. else {
  3795. // 1. Assert: entriesForNavigationAPI is given.
  3796. VERIFY(entries_for_navigation_api.has_value());
  3797. // FIXME: 2. Restore persisted state given entry.
  3798. // 3. Initialize the navigation API entries for a new document given navigation, entriesForNavigationAPI, and entry.
  3799. navigation->initialize_the_navigation_api_entries_for_a_new_document(*entries_for_navigation_api, entry);
  3800. }
  3801. }
  3802. // FIXME: 7. If all the following are true:
  3803. // - previousEntryForActivation is given;
  3804. // - navigationType is non-null; and
  3805. // - navigationType is "reload" or previousEntryForActivation's document is not document, then:
  3806. // FIXME: 1. If navigation's activation is null, then set navigation's activation to a new NavigationActivation object in navigation's relevant realm.
  3807. // FIXME: 2. Let previousEntryIndex be the result of getting the navigation API entry index of previousEntryForActivation within navigation.
  3808. // FIXME: 3. If previousEntryIndex is non-negative, then set activation's old entry to navigation's entry list[previousEntryIndex].
  3809. // FIXME: 4. Otherwise, if all the following are true:
  3810. // - navigationType is "replace";
  3811. // - previousEntryForActivation's document state's origin is same origin with document's origin; and
  3812. // - previousEntryForActivation's document's initial about:blank is false,
  3813. // then set activation's old entry to a new NavigationHistoryEntry in navigation's relevant realm, whose session history entry is previousEntryForActivation.
  3814. // FIXME: 5. Set activation's new entry to navigation's current entry.
  3815. // FIXME: 6. Set activation's navigation type to navigationType.
  3816. // 8. If documentIsNew is true, then:
  3817. if (document_is_new) {
  3818. // 1. Try to scroll to the fragment for document.
  3819. try_to_scroll_to_the_fragment();
  3820. // 2. At this point scripts may run for the newly-created document document.
  3821. m_ready_to_run_scripts = true;
  3822. }
  3823. // 9. Otherwise, if documentsEntryChanged is false and doNotReactivate is false, then:
  3824. // NOTE: This is for bfcache restoration
  3825. if (!documents_entry_changed && !do_not_reactivate) {
  3826. // FIXME: 1. Assert: entriesForNavigationAPI is given.
  3827. // FIXME: 2. Reactivate document given entry and entriesForNavigationAPI.
  3828. }
  3829. }
  3830. HashMap<URL::URL, GC::Ptr<HTML::SharedResourceRequest>>& Document::shared_resource_requests()
  3831. {
  3832. return m_shared_resource_requests;
  3833. }
  3834. // https://www.w3.org/TR/web-animations-1/#dom-document-timeline
  3835. GC::Ref<Animations::DocumentTimeline> Document::timeline()
  3836. {
  3837. // The DocumentTimeline object representing the default document timeline. The default document timeline has an
  3838. // origin time of zero.
  3839. if (!m_default_timeline)
  3840. m_default_timeline = Animations::DocumentTimeline::create(realm(), *this, 0.0);
  3841. return *m_default_timeline;
  3842. }
  3843. void Document::associate_with_timeline(GC::Ref<Animations::AnimationTimeline> timeline)
  3844. {
  3845. m_associated_animation_timelines.set(timeline);
  3846. }
  3847. void Document::disassociate_with_timeline(GC::Ref<Animations::AnimationTimeline> timeline)
  3848. {
  3849. m_associated_animation_timelines.remove(timeline);
  3850. }
  3851. void Document::append_pending_animation_event(Web::DOM::Document::PendingAnimationEvent const& event)
  3852. {
  3853. m_pending_animation_event_queue.append(event);
  3854. }
  3855. // https://www.w3.org/TR/web-animations-1/#update-animations-and-send-events
  3856. void Document::update_animations_and_send_events(Optional<double> const& timestamp)
  3857. {
  3858. // 1. Update the current time of all timelines associated with doc passing now as the timestamp.
  3859. //
  3860. // Note: Due to the hierarchical nature of the timing model, updating the current time of a timeline also involves:
  3861. // - Updating the current time of any animations associated with the timeline.
  3862. // - Running the update an animation’s finished state procedure for any animations whose current time has been
  3863. // updated.
  3864. // - Queueing animation events for any such animations.
  3865. m_last_animation_frame_timestamp = timestamp;
  3866. for (auto const& timeline : m_associated_animation_timelines)
  3867. timeline->set_current_time(timestamp);
  3868. // 2. Remove replaced animations for doc.
  3869. remove_replaced_animations();
  3870. // 3. Perform a microtask checkpoint.
  3871. HTML::perform_a_microtask_checkpoint();
  3872. // 4. Let events to dispatch be a copy of doc’s pending animation event queue.
  3873. auto events_to_dispatch = GC::ConservativeVector<Document::PendingAnimationEvent> { vm().heap() };
  3874. events_to_dispatch.extend(m_pending_animation_event_queue);
  3875. // 5. Clear doc’s pending animation event queue.
  3876. m_pending_animation_event_queue.clear();
  3877. // 6. Perform a stable sort of the animation events in events to dispatch as follows:
  3878. auto sort_events_by_composite_order = [](auto const& a, auto const& b) {
  3879. if (!a.animation->effect())
  3880. return true;
  3881. if (!b.animation->effect())
  3882. return false;
  3883. auto& a_effect = verify_cast<Animations::KeyframeEffect>(*a.animation->effect());
  3884. auto& b_effect = verify_cast<Animations::KeyframeEffect>(*b.animation->effect());
  3885. return Animations::KeyframeEffect::composite_order(a_effect, b_effect) < 0;
  3886. };
  3887. insertion_sort(events_to_dispatch, [&](auto const& a, auto const& b) {
  3888. // Sort the events by their scheduled event time such that events that were scheduled to occur earlier, sort
  3889. // before events scheduled to occur later and events whose scheduled event time is unresolved sort before events
  3890. // with a resolved scheduled event time.
  3891. //
  3892. // Within events with equal scheduled event times, sort by their composite order.
  3893. if (b.scheduled_event_time.has_value()) {
  3894. if (!a.scheduled_event_time.has_value())
  3895. return true;
  3896. auto a_time = a.scheduled_event_time.value();
  3897. auto b_time = b.scheduled_event_time.value();
  3898. if (a_time == b_time)
  3899. return sort_events_by_composite_order(a, b);
  3900. return a.scheduled_event_time.value() < b.scheduled_event_time.value();
  3901. }
  3902. if (a.scheduled_event_time.has_value())
  3903. return false;
  3904. return sort_events_by_composite_order(a, b);
  3905. });
  3906. // 7. Dispatch each of the events in events to dispatch at their corresponding target using the order established in
  3907. // the previous step.
  3908. for (auto const& event : events_to_dispatch)
  3909. event.target->dispatch_event(event.event);
  3910. for (auto& timeline : m_associated_animation_timelines) {
  3911. for (auto& animation : timeline->associated_animations())
  3912. dispatch_events_for_animation_if_necessary(animation);
  3913. }
  3914. }
  3915. // https://www.w3.org/TR/web-animations-1/#remove-replaced-animations
  3916. void Document::remove_replaced_animations()
  3917. {
  3918. // When asked to remove replaced animations for a Document, doc, then for every animation, animation, that:
  3919. // - has an associated animation effect whose effect target is a descendant of doc, and
  3920. // - is replaceable, and
  3921. // - has a replace state of active, and
  3922. // - for which there exists for each target property of every animation effect associated with animation, an
  3923. // animation effect associated with a replaceable animation with a higher composite order than animation that
  3924. // includes the same target property
  3925. Vector<GC::Ref<Animations::Animation>> replaceable_animations;
  3926. for (auto const& timeline : m_associated_animation_timelines) {
  3927. for (auto const& animation : timeline->associated_animations()) {
  3928. if (!animation->effect() || !animation->effect()->target() || &animation->effect()->target()->document() != this)
  3929. continue;
  3930. if (!animation->is_replaceable())
  3931. continue;
  3932. if (animation->replace_state() != Bindings::AnimationReplaceState::Active)
  3933. continue;
  3934. // Composite order is only defined for KeyframeEffects
  3935. if (!animation->effect()->is_keyframe_effect())
  3936. continue;
  3937. replaceable_animations.append(animation);
  3938. }
  3939. }
  3940. quick_sort(replaceable_animations, [](GC::Ref<Animations::Animation>& a, GC::Ref<Animations::Animation>& b) {
  3941. VERIFY(a->effect()->is_keyframe_effect());
  3942. VERIFY(b->effect()->is_keyframe_effect());
  3943. auto& a_effect = *static_cast<Animations::KeyframeEffect*>(a->effect().ptr());
  3944. auto& b_effect = *static_cast<Animations::KeyframeEffect*>(b->effect().ptr());
  3945. return Animations::KeyframeEffect::composite_order(a_effect, b_effect) < 0;
  3946. });
  3947. // Lower value = higher priority
  3948. HashMap<CSS::PropertyID, size_t> highest_property_composite_orders;
  3949. for (int i = replaceable_animations.size() - 1; i >= 0; i--) {
  3950. auto animation = replaceable_animations[i];
  3951. bool has_any_highest_priority_property = false;
  3952. for (auto const& property : animation->effect()->target_properties()) {
  3953. if (!highest_property_composite_orders.contains(property)) {
  3954. has_any_highest_priority_property = true;
  3955. highest_property_composite_orders.set(property, i);
  3956. }
  3957. }
  3958. if (!has_any_highest_priority_property) {
  3959. // perform the following steps:
  3960. // - Set animation’s replace state to removed.
  3961. animation->set_replace_state(Bindings::AnimationReplaceState::Removed);
  3962. // - Create an AnimationPlaybackEvent, removeEvent.
  3963. // - Set removeEvent’s type attribute to remove.
  3964. // - Set removeEvent’s currentTime attribute to the current time of animation.
  3965. // - Set removeEvent’s timelineTime attribute to the current time of the timeline with which animation is
  3966. // associated.
  3967. Animations::AnimationPlaybackEventInit init;
  3968. init.current_time = animation->current_time();
  3969. init.timeline_time = animation->timeline()->current_time();
  3970. auto remove_event = Animations::AnimationPlaybackEvent::create(realm(), HTML::EventNames::remove, init);
  3971. // - If animation has a document for timing, then append removeEvent to its document for timing's pending
  3972. // animation event queue along with its target, animation. For the scheduled event time, use the result of
  3973. // applying the procedure to convert timeline time to origin-relative time to the current time of the
  3974. // timeline with which animation is associated.
  3975. if (auto document = animation->document_for_timing()) {
  3976. PendingAnimationEvent pending_animation_event {
  3977. .event = remove_event,
  3978. .animation = animation,
  3979. .target = animation,
  3980. .scheduled_event_time = animation->timeline()->convert_a_timeline_time_to_an_origin_relative_time(init.timeline_time),
  3981. };
  3982. document->append_pending_animation_event(pending_animation_event);
  3983. }
  3984. // Otherwise, queue a task to dispatch removeEvent at animation. The task source for this task is the DOM
  3985. // manipulation task source.
  3986. else {
  3987. HTML::queue_global_task(HTML::Task::Source::DOMManipulation, realm().global_object(), GC::create_function(heap(), [animation, remove_event]() {
  3988. animation->dispatch_event(remove_event);
  3989. }));
  3990. }
  3991. }
  3992. }
  3993. }
  3994. WebIDL::ExceptionOr<Vector<GC::Ref<Animations::Animation>>> Document::get_animations()
  3995. {
  3996. Vector<GC::Ref<Animations::Animation>> relevant_animations;
  3997. TRY(for_each_child_of_type_fallible<Element>([&](auto& child) -> WebIDL::ExceptionOr<IterationDecision> {
  3998. relevant_animations.extend(TRY(child.get_animations(Animations::GetAnimationsOptions { .subtree = true })));
  3999. return IterationDecision::Continue;
  4000. }));
  4001. return relevant_animations;
  4002. }
  4003. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-nameditem-filter
  4004. static bool is_potentially_named_element(DOM::Element const& element)
  4005. {
  4006. return is<HTML::HTMLEmbedElement>(element) || is<HTML::HTMLFormElement>(element) || is<HTML::HTMLIFrameElement>(element) || is<HTML::HTMLImageElement>(element) || is<HTML::HTMLObjectElement>(element);
  4007. }
  4008. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-nameditem-filter
  4009. static bool is_potentially_named_element_by_id(DOM::Element const& element)
  4010. {
  4011. return is<HTML::HTMLObjectElement>(element) || is<HTML::HTMLImageElement>(element);
  4012. }
  4013. static void insert_in_tree_order(Vector<GC::Ref<DOM::Element>>& elements, DOM::Element& element)
  4014. {
  4015. for (auto& el : elements) {
  4016. if (el == &element)
  4017. return;
  4018. }
  4019. auto index = elements.find_first_index_if([&](auto& existing_element) {
  4020. return existing_element->compare_document_position(element) & Node::DOCUMENT_POSITION_FOLLOWING;
  4021. });
  4022. if (index.has_value())
  4023. elements.insert(index.value(), element);
  4024. else
  4025. elements.append(element);
  4026. }
  4027. void Document::element_id_changed(Badge<DOM::Element>, GC::Ref<DOM::Element> element)
  4028. {
  4029. for (auto* form_associated_element : m_form_associated_elements_with_form_attribute)
  4030. form_associated_element->element_id_changed({});
  4031. if (element->id().has_value())
  4032. insert_in_tree_order(m_potentially_named_elements, element);
  4033. else
  4034. (void)m_potentially_named_elements.remove_first_matching([element](auto& e) { return e == element; });
  4035. }
  4036. void Document::element_with_id_was_added(Badge<DOM::Element>, GC::Ref<DOM::Element> element)
  4037. {
  4038. for (auto* form_associated_element : m_form_associated_elements_with_form_attribute)
  4039. form_associated_element->element_with_id_was_added_or_removed({});
  4040. if (is_potentially_named_element_by_id(*element))
  4041. insert_in_tree_order(m_potentially_named_elements, element);
  4042. }
  4043. void Document::element_with_id_was_removed(Badge<DOM::Element>, GC::Ref<DOM::Element> element)
  4044. {
  4045. for (auto* form_associated_element : m_form_associated_elements_with_form_attribute)
  4046. form_associated_element->element_with_id_was_added_or_removed({});
  4047. if (is_potentially_named_element_by_id(*element))
  4048. (void)m_potentially_named_elements.remove_first_matching([element](auto& e) { return e == element; });
  4049. }
  4050. void Document::element_name_changed(Badge<DOM::Element>, GC::Ref<DOM::Element> element)
  4051. {
  4052. if (element->name().has_value()) {
  4053. insert_in_tree_order(m_potentially_named_elements, element);
  4054. } else {
  4055. if (is_potentially_named_element_by_id(element) && element->id().has_value())
  4056. return;
  4057. (void)m_potentially_named_elements.remove_first_matching([element](auto& e) { return e == element; });
  4058. }
  4059. }
  4060. void Document::element_with_name_was_added(Badge<DOM::Element>, GC::Ref<DOM::Element> element)
  4061. {
  4062. if (is_potentially_named_element(element))
  4063. insert_in_tree_order(m_potentially_named_elements, element);
  4064. }
  4065. void Document::element_with_name_was_removed(Badge<DOM::Element>, GC::Ref<DOM::Element> element)
  4066. {
  4067. if (is_potentially_named_element(element)) {
  4068. if (is_potentially_named_element_by_id(element) && element->id().has_value())
  4069. return;
  4070. (void)m_potentially_named_elements.remove_first_matching([element](auto& e) { return e == element; });
  4071. }
  4072. }
  4073. void Document::add_form_associated_element_with_form_attribute(HTML::FormAssociatedElement& form_associated_element)
  4074. {
  4075. m_form_associated_elements_with_form_attribute.append(&form_associated_element);
  4076. }
  4077. void Document::remove_form_associated_element_with_form_attribute(HTML::FormAssociatedElement& form_associated_element)
  4078. {
  4079. m_form_associated_elements_with_form_attribute.remove_all_matching([&](auto* element) {
  4080. return element == &form_associated_element;
  4081. });
  4082. }
  4083. void Document::set_design_mode_enabled_state(bool design_mode_enabled)
  4084. {
  4085. m_design_mode_enabled = design_mode_enabled;
  4086. set_editable(design_mode_enabled);
  4087. }
  4088. // https://html.spec.whatwg.org/multipage/interaction.html#making-entire-documents-editable:-the-designmode-idl-attribute
  4089. String Document::design_mode() const
  4090. {
  4091. // The designMode getter steps are to return "on" if this's design mode enabled is true; otherwise "off".
  4092. return design_mode_enabled_state() ? "on"_string : "off"_string;
  4093. }
  4094. WebIDL::ExceptionOr<void> Document::set_design_mode(String const& design_mode)
  4095. {
  4096. // 1. Let value be the given value, converted to ASCII lowercase.
  4097. auto value = MUST(design_mode.to_lowercase());
  4098. // 2. If value is "on" and this's design mode enabled is false, then:
  4099. if (value == "on"sv && !m_design_mode_enabled) {
  4100. // 1. Set this's design mode enabled to true.
  4101. set_design_mode_enabled_state(true);
  4102. // 2. Reset this's active range's start and end boundary points to be at the start of this.
  4103. if (auto selection = get_selection(); selection) {
  4104. if (auto active_range = selection->range(); active_range) {
  4105. TRY(active_range->set_start(*this, 0));
  4106. TRY(active_range->set_end(*this, 0));
  4107. update_layout();
  4108. }
  4109. }
  4110. // 3. Run the focusing steps for this's document element, if non-null.
  4111. if (auto* document_element = this->document_element(); document_element)
  4112. HTML::run_focusing_steps(document_element);
  4113. }
  4114. // 3. If value is "off", then set this's design mode enabled to false.
  4115. else if (value == "off"sv) {
  4116. set_design_mode_enabled_state(false);
  4117. }
  4118. return {};
  4119. }
  4120. // https://drafts.csswg.org/cssom-view/#dom-document-elementfrompoint
  4121. Element const* Document::element_from_point(double x, double y)
  4122. {
  4123. // 1. If either argument is negative, x is greater than the viewport width excluding the size of a rendered scroll
  4124. // bar (if any), or y is greater than the viewport height excluding the size of a rendered scroll bar (if any), or
  4125. // there is no viewport associated with the document, return null and terminate these steps.
  4126. auto viewport_rect = this->viewport_rect();
  4127. CSSPixelPoint position { x, y };
  4128. // FIXME: This should account for the size of the scroll bar.
  4129. if (x < 0 || y < 0 || position.x() > viewport_rect.width() || position.y() > viewport_rect.height())
  4130. return nullptr;
  4131. // Ensure the layout tree exists prior to hit testing.
  4132. update_layout();
  4133. // 2. If there is a box in the viewport that would be a target for hit testing at coordinates x,y, when applying the transforms
  4134. // that apply to the descendants of the viewport, return the associated element and terminate these steps.
  4135. Optional<Painting::HitTestResult> hit_test_result;
  4136. if (auto const* paintable_box = this->paintable_box(); paintable_box) {
  4137. (void)paintable_box->hit_test(position, Painting::HitTestType::Exact, [&](Painting::HitTestResult result) {
  4138. auto* dom_node = result.dom_node();
  4139. if (dom_node && dom_node->is_element()) {
  4140. hit_test_result = result;
  4141. return TraversalDecision::Break;
  4142. }
  4143. return TraversalDecision::Continue;
  4144. });
  4145. }
  4146. if (hit_test_result.has_value())
  4147. return static_cast<Element*>(hit_test_result->dom_node());
  4148. // 3. If the document has a root element, return the root element and terminate these steps.
  4149. if (auto const* document_root_element = first_child_of_type<Element>(); document_root_element)
  4150. return document_root_element;
  4151. // 4. Return null.
  4152. return nullptr;
  4153. }
  4154. // https://drafts.csswg.org/cssom-view/#dom-document-elementsfrompoint
  4155. GC::RootVector<GC::Ref<Element>> Document::elements_from_point(double x, double y)
  4156. {
  4157. // 1. Let sequence be a new empty sequence.
  4158. GC::RootVector<GC::Ref<Element>> sequence(heap());
  4159. // 2. If either argument is negative, x is greater than the viewport width excluding the size of a rendered scroll bar (if any),
  4160. // or y is greater than the viewport height excluding the size of a rendered scroll bar (if any),
  4161. // or there is no viewport associated with the document, return sequence and terminate these steps.
  4162. auto viewport_rect = this->viewport_rect();
  4163. CSSPixelPoint position { x, y };
  4164. // FIXME: This should account for the size of the scroll bar.
  4165. if (x < 0 || y < 0 || position.x() > viewport_rect.width() || position.y() > viewport_rect.height())
  4166. return sequence;
  4167. // Ensure the layout tree exists prior to hit testing.
  4168. update_layout();
  4169. // 3. For each box in the viewport, in paint order, starting with the topmost box, that would be a target for
  4170. // hit testing at coordinates x,y even if nothing would be overlapping it, when applying the transforms that
  4171. // apply to the descendants of the viewport, append the associated element to sequence.
  4172. if (auto const* paintable_box = this->paintable_box(); paintable_box) {
  4173. (void)paintable_box->hit_test(position, Painting::HitTestType::Exact, [&](Painting::HitTestResult result) {
  4174. auto* dom_node = result.dom_node();
  4175. if (dom_node && dom_node->is_element())
  4176. sequence.append(*static_cast<Element*>(dom_node));
  4177. return TraversalDecision::Continue;
  4178. });
  4179. }
  4180. // 4. If the document has a root element, and the last item in sequence is not the root element,
  4181. // append the root element to sequence.
  4182. if (auto* root_element = document_element(); root_element && (sequence.is_empty() || (sequence.last() != root_element)))
  4183. sequence.append(*root_element);
  4184. // 5. Return sequence.
  4185. return sequence;
  4186. }
  4187. // https://drafts.csswg.org/cssom-view/#dom-document-scrollingelement
  4188. GC::Ptr<Element const> Document::scrolling_element() const
  4189. {
  4190. // 1. If the Document is in quirks mode, follow these substeps:
  4191. if (in_quirks_mode()) {
  4192. // 1. If the body element exists, and it is not potentially scrollable, return the body element and abort these steps.
  4193. // For this purpose, a value of overflow:clip on the the body element’s parent element must be treated as overflow:hidden.
  4194. if (auto const* body_element = body(); body_element && !body_element->is_potentially_scrollable())
  4195. return body_element;
  4196. // 2. Return null and abort these steps.
  4197. return nullptr;
  4198. }
  4199. // 2. If there is a root element, return the root element and abort these steps.
  4200. if (auto const* root_element = document_element(); root_element)
  4201. return root_element;
  4202. // 3. Return null.
  4203. return nullptr;
  4204. }
  4205. // https://html.spec.whatwg.org/multipage/dom.html#exposed
  4206. static bool is_exposed(Element const& element)
  4207. {
  4208. VERIFY(is<HTML::HTMLEmbedElement>(element) || is<HTML::HTMLObjectElement>(element));
  4209. // FIXME: An embed or object element is said to be exposed if it has no exposed object ancestor, and,
  4210. // for object elements, is additionally either not showing its fallback content or has no object or embed descendants.
  4211. return true;
  4212. }
  4213. // https://html.spec.whatwg.org/multipage/dom.html#dom-tree-accessors:supported-property-names
  4214. Vector<FlyString> Document::supported_property_names() const
  4215. {
  4216. // The supported property names of a Document object document at any moment consist of the following,
  4217. // in tree order according to the element that contributed them, ignoring later duplicates,
  4218. // and with values from id attributes coming before values from name attributes when the same element contributes both:
  4219. OrderedHashTable<FlyString> names;
  4220. for (auto const& element : m_potentially_named_elements) {
  4221. // - the value of the name content attribute for all exposed embed, form, iframe, img, and exposed object elements
  4222. // that have a non-empty name content attribute and are in a document tree with document as their root;
  4223. if ((is<HTML::HTMLEmbedElement>(*element) && is_exposed(element))
  4224. || is<HTML::HTMLFormElement>(*element)
  4225. || is<HTML::HTMLIFrameElement>(*element)
  4226. || is<HTML::HTMLImageElement>(*element)
  4227. || (is<HTML::HTMLObjectElement>(*element) && is_exposed(element))) {
  4228. if (auto name = element->name(); name.has_value()) {
  4229. names.set(name.value());
  4230. }
  4231. }
  4232. // - the value of the id content attribute for all exposed object elements that have a non-empty id content attribute
  4233. // and are in a document tree with document as their root; and
  4234. if (is<HTML::HTMLObjectElement>(*element) && is_exposed(element)) {
  4235. if (auto id = element->id(); id.has_value()) {
  4236. names.set(id.value());
  4237. }
  4238. }
  4239. // - the value of the id content attribute for all img elements that have both a non-empty id content attribute
  4240. // and a non-empty name content attribute, and are in a document tree with document as their root.
  4241. if (is<HTML::HTMLImageElement>(*element)) {
  4242. if (auto id = element->id(); id.has_value() && element->name().has_value()) {
  4243. names.set(id.value());
  4244. }
  4245. }
  4246. }
  4247. return names.values();
  4248. }
  4249. static bool is_named_element_with_name(Element const& element, FlyString const& name)
  4250. {
  4251. // Named elements with the name name, for the purposes of the above algorithm, are those that are either:
  4252. // - Exposed embed, form, iframe, img, or exposed object elements that have a name content attribute whose value
  4253. // is name, or
  4254. if ((is<HTML::HTMLEmbedElement>(element) && is_exposed(element))
  4255. || is<HTML::HTMLFormElement>(element)
  4256. || is<HTML::HTMLIFrameElement>(element)
  4257. || is<HTML::HTMLImageElement>(element)
  4258. || (is<HTML::HTMLObjectElement>(element) && is_exposed(element))) {
  4259. if (element.name() == name)
  4260. return true;
  4261. }
  4262. // - Exposed object elements that have an id content attribute whose value is name, or
  4263. if (is<HTML::HTMLObjectElement>(element) && is_exposed(element)) {
  4264. if (element.id() == name)
  4265. return true;
  4266. }
  4267. // - img elements that have an id content attribute whose value is name, and that have a non-empty name content
  4268. // attribute present also.
  4269. if (is<HTML::HTMLImageElement>(element)) {
  4270. if (element.id() == name && element.name().has_value())
  4271. return true;
  4272. }
  4273. return false;
  4274. }
  4275. static Vector<GC::Ref<DOM::Element>> named_elements_with_name(Document const& document, FlyString const& name)
  4276. {
  4277. Vector<GC::Ref<DOM::Element>> named_elements;
  4278. for (auto const& element : document.potentially_named_elements()) {
  4279. if (is_named_element_with_name(element, name))
  4280. named_elements.append(element);
  4281. }
  4282. return named_elements;
  4283. }
  4284. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-nameditem
  4285. JS::Value Document::named_item_value(FlyString const& name) const
  4286. {
  4287. // 1. Let elements be the list of named elements with the name name that are in a document tree with the Document as their root.
  4288. // NOTE: There will be at least one such element, since the algorithm would otherwise not have been invoked by Web IDL.
  4289. auto elements = named_elements_with_name(*this, name);
  4290. // 2. If elements has only one element, and that element is an iframe element, and that iframe element's content navigable is not null,
  4291. // then return the active WindowProxy of the element's content navigable.
  4292. if (elements.size() == 1 && is<HTML::HTMLIFrameElement>(*elements.first())) {
  4293. auto& iframe_element = static_cast<HTML::HTMLIFrameElement&>(*elements.first());
  4294. if (iframe_element.content_navigable() != nullptr)
  4295. return iframe_element.content_navigable()->active_window_proxy();
  4296. }
  4297. // 3. Otherwise, if elements has only one element, return that element.
  4298. if (elements.size() == 1)
  4299. return elements.first();
  4300. // 4. Otherwise return an HTMLCollection rooted at the Document node, whose filter matches only named elements with the name name.
  4301. return HTMLCollection::create(*const_cast<Document*>(this), HTMLCollection::Scope::Descendants, [name](auto& element) {
  4302. return is_named_element_with_name(element, name);
  4303. });
  4304. }
  4305. // https://drafts.csswg.org/resize-observer-1/#calculate-depth-for-node
  4306. static size_t calculate_depth_for_node(Node const& node)
  4307. {
  4308. // 1. Let p be the parent-traversal path from node to a root Element of this element’s flattened DOM tree.
  4309. // 2. Return number of nodes in p.
  4310. size_t depth = 0;
  4311. for (auto const* current = &node; current; current = current->parent())
  4312. ++depth;
  4313. return depth;
  4314. }
  4315. // https://drafts.csswg.org/resize-observer-1/#gather-active-observations-h
  4316. void Document::gather_active_observations_at_depth(size_t depth)
  4317. {
  4318. // 1. Let depth be the depth passed in.
  4319. // 2. For each observer in [[resizeObservers]] run these steps:
  4320. for (auto const& observer : m_resize_observers) {
  4321. // 1. Clear observer’s [[activeTargets]], and [[skippedTargets]].
  4322. observer->active_targets().clear();
  4323. observer->skipped_targets().clear();
  4324. // 2. For each observation in observer.[[observationTargets]] run this step:
  4325. for (auto const& observation : observer->observation_targets()) {
  4326. // 1. If observation.isActive() is true
  4327. if (observation->is_active()) {
  4328. // 1. Let targetDepth be result of calculate depth for node for observation.target.
  4329. auto target_depth = calculate_depth_for_node(*observation->target());
  4330. // 2. If targetDepth is greater than depth then add observation to [[activeTargets]].
  4331. if (target_depth > depth) {
  4332. observer->active_targets().append(observation);
  4333. } else {
  4334. // 3. Else add observation to [[skippedTargets]].
  4335. observer->skipped_targets().append(observation);
  4336. }
  4337. }
  4338. }
  4339. }
  4340. }
  4341. // https://drafts.csswg.org/resize-observer-1/#broadcast-active-resize-observations
  4342. size_t Document::broadcast_active_resize_observations()
  4343. {
  4344. // 1. Let shallowestTargetDepth be ∞
  4345. auto shallowest_target_depth = NumericLimits<size_t>::max();
  4346. // 2. For each observer in document.[[resizeObservers]] run these steps:
  4347. // NOTE: We make a copy of the resize observers list to avoid modifying it while iterating.
  4348. GC::RootVector<GC::Ref<ResizeObserver::ResizeObserver>> resize_observers(heap());
  4349. resize_observers.ensure_capacity(m_resize_observers.size());
  4350. for (auto const& observer : m_resize_observers)
  4351. resize_observers.append(observer);
  4352. for (auto const& observer : resize_observers) {
  4353. // 1. If observer.[[activeTargets]] slot is empty, continue.
  4354. if (observer->active_targets().is_empty()) {
  4355. continue;
  4356. }
  4357. // 2. Let entries be an empty list of ResizeObserverEntryies.
  4358. GC::RootVector<GC::Ref<ResizeObserver::ResizeObserverEntry>> entries(heap());
  4359. // 3. For each observation in [[activeTargets]] perform these steps:
  4360. for (auto const& observation : observer->active_targets()) {
  4361. // 1. Let entry be the result of running create and populate a ResizeObserverEntry given observation.target.
  4362. auto entry = ResizeObserver::ResizeObserverEntry::create_and_populate(realm(), *observation->target()).release_value_but_fixme_should_propagate_errors();
  4363. // 2. Add entry to entries.
  4364. entries.append(entry);
  4365. // 3. Set observation.lastReportedSizes to matching entry sizes.
  4366. switch (observation->observed_box()) {
  4367. case Bindings::ResizeObserverBoxOptions::BorderBox:
  4368. // Matching sizes are entry.borderBoxSize if observation.observedBox is "border-box"
  4369. observation->last_reported_sizes() = entry->border_box_size();
  4370. break;
  4371. case Bindings::ResizeObserverBoxOptions::ContentBox:
  4372. // Matching sizes are entry.contentBoxSize if observation.observedBox is "content-box"
  4373. observation->last_reported_sizes() = entry->content_box_size();
  4374. break;
  4375. case Bindings::ResizeObserverBoxOptions::DevicePixelContentBox:
  4376. // Matching sizes are entry.devicePixelContentBoxSize if observation.observedBox is "device-pixel-content-box"
  4377. observation->last_reported_sizes() = entry->device_pixel_content_box_size();
  4378. break;
  4379. default:
  4380. VERIFY_NOT_REACHED();
  4381. }
  4382. // 4. Set targetDepth to the result of calculate depth for node for observation.target.
  4383. auto target_depth = calculate_depth_for_node(*observation->target());
  4384. // 5. Set shallowestTargetDepth to targetDepth if targetDepth < shallowestTargetDepth
  4385. if (target_depth < shallowest_target_depth)
  4386. shallowest_target_depth = target_depth;
  4387. }
  4388. // 4. Invoke observer.[[callback]] with entries.
  4389. observer->invoke_callback(entries);
  4390. // 5. Clear observer.[[activeTargets]].
  4391. observer->active_targets().clear();
  4392. }
  4393. return shallowest_target_depth;
  4394. }
  4395. // https://drafts.csswg.org/resize-observer-1/#has-active-observations-h
  4396. bool Document::has_active_resize_observations()
  4397. {
  4398. // 1. For each observer in [[resizeObservers]] run this step:
  4399. for (auto const& observer : m_resize_observers) {
  4400. // 1. If observer.[[activeTargets]] is not empty, return true.
  4401. if (!observer->active_targets().is_empty())
  4402. return true;
  4403. }
  4404. // 2. Return false.
  4405. return false;
  4406. }
  4407. // https://drafts.csswg.org/resize-observer-1/#has-skipped-observations-h
  4408. bool Document::has_skipped_resize_observations()
  4409. {
  4410. // 1. For each observer in [[resizeObservers]] run this step:
  4411. for (auto const& observer : m_resize_observers) {
  4412. // 1. If observer.[[skippedTargets]] is not empty, return true.
  4413. if (!observer->skipped_targets().is_empty())
  4414. return true;
  4415. }
  4416. // 2. Return false.
  4417. return false;
  4418. }
  4419. GC::Ref<WebIDL::ObservableArray> Document::adopted_style_sheets() const
  4420. {
  4421. if (!m_adopted_style_sheets)
  4422. m_adopted_style_sheets = create_adopted_style_sheets_list(const_cast<Document&>(*this));
  4423. return *m_adopted_style_sheets;
  4424. }
  4425. WebIDL::ExceptionOr<void> Document::set_adopted_style_sheets(JS::Value new_value)
  4426. {
  4427. if (!m_adopted_style_sheets)
  4428. m_adopted_style_sheets = create_adopted_style_sheets_list(const_cast<Document&>(*this));
  4429. m_adopted_style_sheets->clear();
  4430. auto iterator_record = TRY(get_iterator(vm(), new_value, JS::IteratorHint::Sync));
  4431. while (true) {
  4432. auto next = TRY(iterator_step_value(vm(), iterator_record));
  4433. if (!next.has_value())
  4434. break;
  4435. TRY(m_adopted_style_sheets->append(*next));
  4436. }
  4437. return {};
  4438. }
  4439. void Document::for_each_active_css_style_sheet(Function<void(CSS::CSSStyleSheet&, GC::Ptr<DOM::ShadowRoot>)>&& callback) const
  4440. {
  4441. if (m_style_sheets) {
  4442. for (auto& style_sheet : m_style_sheets->sheets()) {
  4443. if (!(style_sheet->is_alternate() && style_sheet->disabled()))
  4444. callback(*style_sheet, {});
  4445. }
  4446. }
  4447. if (m_adopted_style_sheets) {
  4448. m_adopted_style_sheets->for_each<CSS::CSSStyleSheet>([&](auto& style_sheet) {
  4449. if (!style_sheet.disabled())
  4450. callback(style_sheet, {});
  4451. });
  4452. }
  4453. for_each_shadow_root([&](auto& shadow_root) {
  4454. shadow_root.for_each_css_style_sheet([&](auto& style_sheet) {
  4455. if (!style_sheet.disabled())
  4456. callback(style_sheet, &shadow_root);
  4457. });
  4458. });
  4459. }
  4460. static Optional<CSS::CSSStyleSheet&> find_style_sheet_with_url(String const& url, CSS::CSSStyleSheet& style_sheet)
  4461. {
  4462. if (style_sheet.location() == url)
  4463. return style_sheet;
  4464. for (auto& import_rule : style_sheet.import_rules()) {
  4465. if (import_rule->loaded_style_sheet()) {
  4466. if (auto match = find_style_sheet_with_url(url, *import_rule->loaded_style_sheet()); match.has_value())
  4467. return match;
  4468. }
  4469. }
  4470. return {};
  4471. }
  4472. Optional<String> Document::get_style_sheet_source(CSS::StyleSheetIdentifier const& identifier) const
  4473. {
  4474. switch (identifier.type) {
  4475. case CSS::StyleSheetIdentifier::Type::StyleElement:
  4476. if (identifier.dom_element_unique_id.has_value()) {
  4477. if (auto* node = Node::from_unique_id(*identifier.dom_element_unique_id)) {
  4478. if (node->is_html_style_element()) {
  4479. if (auto* sheet = verify_cast<HTML::HTMLStyleElement>(*node).sheet())
  4480. return sheet->source_text({});
  4481. }
  4482. if (node->is_svg_style_element()) {
  4483. if (auto* sheet = verify_cast<SVG::SVGStyleElement>(*node).sheet())
  4484. return sheet->source_text({});
  4485. }
  4486. }
  4487. }
  4488. return {};
  4489. case CSS::StyleSheetIdentifier::Type::LinkElement:
  4490. case CSS::StyleSheetIdentifier::Type::ImportRule: {
  4491. if (!identifier.url.has_value()) {
  4492. dbgln("Attempting to get link or imported style-sheet with no url; giving up");
  4493. return {};
  4494. }
  4495. if (m_style_sheets) {
  4496. for (auto& style_sheet : m_style_sheets->sheets()) {
  4497. if (auto match = find_style_sheet_with_url(identifier.url.value(), style_sheet); match.has_value())
  4498. return match->source_text({});
  4499. }
  4500. }
  4501. if (m_adopted_style_sheets) {
  4502. Optional<String> result;
  4503. m_adopted_style_sheets->for_each<CSS::CSSStyleSheet>([&](auto& style_sheet) {
  4504. if (result.has_value())
  4505. return;
  4506. if (auto match = find_style_sheet_with_url(identifier.url.value(), style_sheet); match.has_value())
  4507. result = match->source_text({});
  4508. });
  4509. return result;
  4510. }
  4511. return {};
  4512. }
  4513. case CSS::StyleSheetIdentifier::Type::UserAgent:
  4514. return CSS::StyleComputer::user_agent_style_sheet_source(identifier.url.value());
  4515. case CSS::StyleSheetIdentifier::Type::UserStyle:
  4516. return page().user_style();
  4517. }
  4518. return {};
  4519. }
  4520. void Document::register_shadow_root(Badge<DOM::ShadowRoot>, DOM::ShadowRoot& shadow_root)
  4521. {
  4522. m_shadow_roots.append(shadow_root);
  4523. }
  4524. void Document::unregister_shadow_root(Badge<DOM::ShadowRoot>, DOM::ShadowRoot& shadow_root)
  4525. {
  4526. m_shadow_roots.remove_all_matching([&](auto& item) {
  4527. return item.ptr() == &shadow_root;
  4528. });
  4529. }
  4530. void Document::for_each_shadow_root(Function<void(DOM::ShadowRoot&)>&& callback)
  4531. {
  4532. for (auto& shadow_root : m_shadow_roots)
  4533. callback(shadow_root);
  4534. }
  4535. void Document::for_each_shadow_root(Function<void(DOM::ShadowRoot&)>&& callback) const
  4536. {
  4537. for (auto& shadow_root : m_shadow_roots)
  4538. callback(shadow_root);
  4539. }
  4540. bool Document::is_decoded_svg() const
  4541. {
  4542. return is<Web::SVG::SVGDecodedImageData::SVGPageClient>(page().client());
  4543. }
  4544. // https://drafts.csswg.org/css-position-4/#add-an-element-to-the-top-layer
  4545. void Document::add_an_element_to_the_top_layer(GC::Ref<Element> element)
  4546. {
  4547. // 1. Let doc be el’s node document.
  4548. // 2. If el is already contained in doc’s top layer:
  4549. if (m_top_layer_elements.contains(element)) {
  4550. // Assert: el is also in doc’s pending top layer removals. (Otherwise, this is a spec error.)
  4551. VERIFY(m_top_layer_pending_removals.contains(element));
  4552. // Remove el from both doc’s top layer and pending top layer removals.
  4553. m_top_layer_elements.remove(element);
  4554. m_top_layer_pending_removals.remove(element);
  4555. }
  4556. // 3. Append el to doc’s top layer.
  4557. m_top_layer_elements.set(element);
  4558. element->set_in_top_layer(true);
  4559. // FIXME: 4. At the UA !important cascade origin, add a rule targeting el containing an overlay: auto declaration.
  4560. }
  4561. // https://drafts.csswg.org/css-position-4/#request-an-element-to-be-removed-from-the-top-layer
  4562. void Document::request_an_element_to_be_remove_from_the_top_layer(GC::Ref<Element> element)
  4563. {
  4564. // 1. Let doc be el’s node document.
  4565. // 2. If el is not contained doc’s top layer, or el is already contained in doc’s pending top layer removals, return.
  4566. if (!m_top_layer_elements.contains(element) || m_top_layer_pending_removals.contains(element))
  4567. return;
  4568. // FIXME: 3. Remove the UA !important overlay: auto rule targeting el.
  4569. // 4. Append el to doc’s pending top layer removals.
  4570. m_top_layer_pending_removals.set(element);
  4571. }
  4572. // https://drafts.csswg.org/css-position-4/#remove-an-element-from-the-top-layer-immediately
  4573. void Document::remove_an_element_from_the_top_layer_immediately(GC::Ref<Element> element)
  4574. {
  4575. // 1. Let doc be el’s node document.
  4576. // 2. Remove el from doc’s top layer and pending top layer removals.
  4577. m_top_layer_elements.remove(element);
  4578. element->set_in_top_layer(false);
  4579. // FIXME: 3. Remove the UA !important overlay: auto rule targeting el, if it exists.
  4580. }
  4581. // https://drafts.csswg.org/css-position-4/#process-top-layer-removals
  4582. void Document::process_top_layer_removals()
  4583. {
  4584. // 1. For each element el in doc’s pending top layer removals: if el’s computed value of overlay is none, or el is
  4585. // not rendered, remove el from doc’s top layer and pending top layer removals.
  4586. for (auto& element : m_top_layer_pending_removals) {
  4587. // FIXME: Check overlay property
  4588. if (!element->paintable()) {
  4589. m_top_layer_elements.remove(element);
  4590. m_top_layer_pending_removals.remove(element);
  4591. element->set_in_top_layer(false);
  4592. }
  4593. }
  4594. }
  4595. void Document::set_needs_to_refresh_scroll_state(bool b)
  4596. {
  4597. if (auto* paintable = this->paintable())
  4598. paintable->set_needs_to_refresh_scroll_state(b);
  4599. }
  4600. Vector<GC::Root<DOM::Range>> Document::find_matching_text(String const& query, CaseSensitivity case_sensitivity)
  4601. {
  4602. // Ensure the layout tree exists before searching for text matches.
  4603. update_layout();
  4604. if (!layout_node())
  4605. return {};
  4606. auto const& text_blocks = layout_node()->text_blocks();
  4607. if (text_blocks.is_empty())
  4608. return {};
  4609. Vector<GC::Root<DOM::Range>> matches;
  4610. for (auto const& text_block : text_blocks) {
  4611. size_t offset = 0;
  4612. size_t i = 0;
  4613. auto const& text = text_block.text;
  4614. auto* match_start_position = &text_block.positions[0];
  4615. while (true) {
  4616. auto match_index = case_sensitivity == CaseSensitivity::CaseInsensitive
  4617. ? text.find_byte_offset_ignoring_case(query, offset)
  4618. : text.find_byte_offset(query, offset);
  4619. if (!match_index.has_value())
  4620. break;
  4621. for (; i < text_block.positions.size() - 1 && match_index.value() > text_block.positions[i + 1].start_offset; ++i)
  4622. match_start_position = &text_block.positions[i + 1];
  4623. auto start_position = match_index.value() - match_start_position->start_offset;
  4624. auto& start_dom_node = match_start_position->dom_node;
  4625. auto* match_end_position = match_start_position;
  4626. for (; i < text_block.positions.size() - 1 && (match_index.value() + query.bytes_as_string_view().length() > text_block.positions[i + 1].start_offset); ++i)
  4627. match_end_position = &text_block.positions[i + 1];
  4628. auto& end_dom_node = match_end_position->dom_node;
  4629. auto end_position = match_index.value() + query.bytes_as_string_view().length() - match_end_position->start_offset;
  4630. matches.append(Range::create(start_dom_node, start_position, end_dom_node, end_position));
  4631. match_start_position = match_end_position;
  4632. offset = match_index.value() + query.bytes_as_string_view().length() + 1;
  4633. if (offset >= text.bytes_as_string_view().length())
  4634. break;
  4635. }
  4636. }
  4637. return matches;
  4638. }
  4639. // https://dom.spec.whatwg.org/#document-allow-declarative-shadow-roots
  4640. bool Document::allow_declarative_shadow_roots() const
  4641. {
  4642. return m_allow_declarative_shadow_roots;
  4643. }
  4644. // https://dom.spec.whatwg.org/#document-allow-declarative-shadow-roots
  4645. void Document::set_allow_declarative_shadow_roots(bool allow)
  4646. {
  4647. m_allow_declarative_shadow_roots = allow;
  4648. }
  4649. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#parse-html-from-a-string
  4650. void Document::parse_html_from_a_string(StringView html)
  4651. {
  4652. // 1. Set document's type to "html".
  4653. set_document_type(DOM::Document::Type::HTML);
  4654. // 2. Create an HTML parser parser, associated with document.
  4655. // 3. Place html into the input stream for parser. The encoding confidence is irrelevant.
  4656. // FIXME: We don't have the concept of encoding confidence yet.
  4657. auto parser = HTML::HTMLParser::create(*this, html, "UTF-8"sv);
  4658. // 4. Start parser and let it run until it has consumed all the characters just inserted into the input stream.
  4659. parser->run(verify_cast<HTML::Window>(HTML::relevant_global_object(*this)).associated_document().url());
  4660. }
  4661. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-parsehtmlunsafe
  4662. GC::Ref<Document> Document::parse_html_unsafe(JS::VM& vm, StringView html)
  4663. {
  4664. auto& realm = *vm.current_realm();
  4665. // FIXME: 1. Let compliantHTML to the result of invoking the Get Trusted Type compliant string algorithm with TrustedHTML, this's relevant global object, html, "Document parseHTMLUnsafe", and "script".
  4666. // 2. Let document be a new Document, whose content type is "text/html".
  4667. auto document = Document::create_for_fragment_parsing(realm);
  4668. document->set_content_type("text/html"_string);
  4669. // 3. Set document's allow declarative shadow roots to true.
  4670. document->set_allow_declarative_shadow_roots(true);
  4671. // 4. Parse HTML from a string given document and compliantHTML. // FIXME: Use compliantHTML.
  4672. document->parse_html_from_a_string(html);
  4673. // 5. Return document.
  4674. return document;
  4675. }
  4676. InputEventsTarget* Document::active_input_events_target()
  4677. {
  4678. auto* focused_element = this->focused_element();
  4679. if (!focused_element)
  4680. return {};
  4681. if (is<HTML::HTMLInputElement>(*focused_element))
  4682. return static_cast<HTML::HTMLInputElement*>(focused_element);
  4683. if (is<HTML::HTMLTextAreaElement>(*focused_element))
  4684. return static_cast<HTML::HTMLTextAreaElement*>(focused_element);
  4685. if (focused_element->is_editable_or_editing_host())
  4686. return m_editing_host_manager;
  4687. return nullptr;
  4688. }
  4689. GC::Ptr<DOM::Position> Document::cursor_position() const
  4690. {
  4691. auto const* focused_element = this->focused_element();
  4692. if (!focused_element)
  4693. return nullptr;
  4694. Optional<HTML::FormAssociatedTextControlElement const&> target {};
  4695. if (is<HTML::HTMLInputElement>(*focused_element))
  4696. target = static_cast<HTML::HTMLInputElement const&>(*focused_element);
  4697. else if (is<HTML::HTMLTextAreaElement>(*focused_element))
  4698. target = static_cast<HTML::HTMLTextAreaElement const&>(*focused_element);
  4699. if (target.has_value())
  4700. return target->cursor_position();
  4701. if (focused_element->is_editable_or_editing_host())
  4702. return m_selection->cursor_position();
  4703. return nullptr;
  4704. }
  4705. void Document::reset_cursor_blink_cycle()
  4706. {
  4707. m_cursor_blink_state = true;
  4708. m_cursor_blink_timer->restart();
  4709. }
  4710. // https://html.spec.whatwg.org/multipage/document-sequences.html#doc-container-document
  4711. GC::Ptr<DOM::Document> Document::container_document() const
  4712. {
  4713. // 1. If document's node navigable is null, then return null.
  4714. auto node_navigable = navigable();
  4715. if (!node_navigable)
  4716. return nullptr;
  4717. // 2. Return document's node navigable's container document.
  4718. return node_navigable->container_document();
  4719. }
  4720. GC::Ptr<HTML::Navigable> Document::cached_navigable()
  4721. {
  4722. return m_cached_navigable.ptr();
  4723. }
  4724. void Document::set_cached_navigable(GC::Ptr<HTML::Navigable> navigable)
  4725. {
  4726. m_cached_navigable = navigable.ptr();
  4727. }
  4728. void Document::set_needs_display(InvalidateDisplayList should_invalidate_display_list)
  4729. {
  4730. set_needs_display(viewport_rect(), should_invalidate_display_list);
  4731. }
  4732. void Document::set_needs_display(CSSPixelRect const&, InvalidateDisplayList should_invalidate_display_list)
  4733. {
  4734. // FIXME: Ignore updates outside the visible viewport rect.
  4735. // This requires accounting for fixed-position elements in the input rect, which we don't do yet.
  4736. m_needs_repaint = true;
  4737. if (should_invalidate_display_list == InvalidateDisplayList::Yes) {
  4738. invalidate_display_list();
  4739. }
  4740. auto navigable = this->navigable();
  4741. if (!navigable)
  4742. return;
  4743. if (navigable->is_traversable()) {
  4744. Web::HTML::main_thread_event_loop().schedule();
  4745. return;
  4746. }
  4747. if (auto container = navigable->container()) {
  4748. container->document().set_needs_display(should_invalidate_display_list);
  4749. }
  4750. }
  4751. void Document::invalidate_display_list()
  4752. {
  4753. m_cached_display_list.clear();
  4754. auto navigable = this->navigable();
  4755. if (!navigable)
  4756. return;
  4757. if (auto container = navigable->container()) {
  4758. container->document().invalidate_display_list();
  4759. }
  4760. }
  4761. RefPtr<Painting::DisplayList> Document::record_display_list(PaintConfig config)
  4762. {
  4763. if (m_cached_display_list && m_cached_display_list_paint_config == config)
  4764. return m_cached_display_list;
  4765. auto display_list = Painting::DisplayList::create();
  4766. Painting::DisplayListRecorder display_list_recorder(display_list);
  4767. if (config.canvas_fill_rect.has_value()) {
  4768. display_list_recorder.fill_rect(config.canvas_fill_rect.value(), CSS::SystemColor::canvas());
  4769. }
  4770. auto viewport_rect = page().css_to_device_rect(this->viewport_rect());
  4771. Gfx::IntRect bitmap_rect { {}, viewport_rect.size().to_type<int>() };
  4772. display_list_recorder.fill_rect(bitmap_rect, background_color());
  4773. if (!paintable()) {
  4774. VERIFY_NOT_REACHED();
  4775. }
  4776. Web::PaintContext context(display_list_recorder, page().palette(), page().client().device_pixels_per_css_pixel());
  4777. context.set_device_viewport_rect(viewport_rect);
  4778. context.set_should_show_line_box_borders(config.should_show_line_box_borders);
  4779. context.set_should_paint_overlay(config.paint_overlay);
  4780. context.set_has_focus(config.has_focus);
  4781. update_paint_and_hit_testing_properties_if_needed();
  4782. auto& viewport_paintable = *paintable();
  4783. viewport_paintable.refresh_scroll_state();
  4784. viewport_paintable.paint_all_phases(context);
  4785. display_list->set_device_pixels_per_css_pixel(page().client().device_pixels_per_css_pixel());
  4786. display_list->set_scroll_state(viewport_paintable.scroll_state());
  4787. m_needs_repaint = false;
  4788. m_cached_display_list = display_list;
  4789. m_cached_display_list_paint_config = config;
  4790. return display_list;
  4791. }
  4792. Unicode::Segmenter& Document::grapheme_segmenter() const
  4793. {
  4794. if (!m_grapheme_segmenter)
  4795. m_grapheme_segmenter = Unicode::Segmenter::create(Unicode::SegmenterGranularity::Grapheme);
  4796. return *m_grapheme_segmenter;
  4797. }
  4798. Unicode::Segmenter& Document::word_segmenter() const
  4799. {
  4800. if (!m_word_segmenter)
  4801. m_word_segmenter = Unicode::Segmenter::create(Unicode::SegmenterGranularity::Word);
  4802. return *m_word_segmenter;
  4803. }
  4804. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#steps-to-fire-beforeunload
  4805. Document::StepsToFireBeforeunloadResult Document::steps_to_fire_beforeunload(bool unload_prompt_shown)
  4806. {
  4807. // 1. Let unloadPromptCanceled be false.
  4808. auto unload_prompt_canceled = false;
  4809. // 2. Increase the document's unload counter by 1.
  4810. m_unload_counter++;
  4811. // 3. Increase document's relevant agent's event loop's termination nesting level by 1.
  4812. auto& event_loop = *verify_cast<Bindings::WebEngineCustomData>(*HTML::relevant_agent(*this).custom_data()).event_loop;
  4813. event_loop.increment_termination_nesting_level();
  4814. // 4. Let eventFiringResult be the result of firing an event named beforeunload at document's relevant global object,
  4815. // using BeforeUnloadEvent, with the cancelable attribute initialized to true.
  4816. auto& global_object = HTML::relevant_global_object(*this);
  4817. auto& window = verify_cast<HTML::Window>(global_object);
  4818. auto beforeunload_event = HTML::BeforeUnloadEvent::create(realm(), HTML::EventNames::beforeunload);
  4819. beforeunload_event->set_cancelable(true);
  4820. auto event_firing_result = window.dispatch_event(*beforeunload_event);
  4821. // 5. Decrease document's relevant agent's event loop's termination nesting level by 1.
  4822. event_loop.decrement_termination_nesting_level();
  4823. // FIXME: 6. If all of the following are true:
  4824. if (false &&
  4825. // - unloadPromptShown is false;
  4826. !unload_prompt_shown
  4827. // - document's active sandboxing flag set does not have its sandboxed modals flag set;
  4828. && !has_flag(document().active_sandboxing_flag_set(), HTML::SandboxingFlagSet::SandboxedModals)
  4829. // - document's relevant global object has sticky activation;
  4830. && window.has_sticky_activation()
  4831. // - eventFiringResult is false, or the returnValue attribute of event is not the empty string; and
  4832. && (!event_firing_result || !beforeunload_event->return_value().is_empty())
  4833. // - FIXME: showing an unload prompt is unlikely to be annoying, deceptive, or pointless
  4834. ) {
  4835. // FIXME: 1. Set unloadPromptShown to true.
  4836. // FIXME: 2. Invoke WebDriver BiDi user prompt opened with document's relevant global object, "beforeunload", and "".
  4837. // FIXME: 3. Ask the user to confirm that they wish to unload the document, and pause while waiting for the user's response.
  4838. // FIXME: 4. If the user did not confirm the page navigation, set unloadPromptCanceled to true.
  4839. // FIXME: 5. Invoke WebDriver BiDi user prompt closed with document's relevant global object and true if unloadPromptCanceled is false or false otherwise.
  4840. }
  4841. // 7. Decrease document's unload counter by 1.
  4842. m_unload_counter--;
  4843. // 8. Return (unloadPromptShown, unloadPromptCanceled).
  4844. return { unload_prompt_shown, unload_prompt_canceled };
  4845. }
  4846. WebIDL::CallbackType* Document::onreadystatechange()
  4847. {
  4848. return event_handler_attribute(HTML::EventNames::readystatechange);
  4849. }
  4850. void Document::set_onreadystatechange(WebIDL::CallbackType* value)
  4851. {
  4852. set_event_handler_attribute(HTML::EventNames::readystatechange, value);
  4853. }
  4854. WebIDL::CallbackType* Document::onvisibilitychange()
  4855. {
  4856. return event_handler_attribute(HTML::EventNames::visibilitychange);
  4857. }
  4858. void Document::set_onvisibilitychange(WebIDL::CallbackType* value)
  4859. {
  4860. set_event_handler_attribute(HTML::EventNames::visibilitychange, value);
  4861. }
  4862. }