Document.cpp 251 KB

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