Document.cpp 244 KB

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