Document.cpp 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400
  1. /*
  2. * Copyright (c) 2018-2023, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021-2023, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
  5. * Copyright (c) 2021, Sam Atkins <atkinssj@serenityos.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/CharacterTypes.h>
  10. #include <AK/Debug.h>
  11. #include <AK/StringBuilder.h>
  12. #include <AK/Utf8View.h>
  13. #include <LibJS/Interpreter.h>
  14. #include <LibJS/Runtime/FunctionObject.h>
  15. #include <LibWeb/Bindings/MainThreadVM.h>
  16. #include <LibWeb/CSS/MediaQueryList.h>
  17. #include <LibWeb/CSS/MediaQueryListEvent.h>
  18. #include <LibWeb/CSS/StyleComputer.h>
  19. #include <LibWeb/Cookie/ParsedCookie.h>
  20. #include <LibWeb/DOM/Comment.h>
  21. #include <LibWeb/DOM/CustomEvent.h>
  22. #include <LibWeb/DOM/DOMImplementation.h>
  23. #include <LibWeb/DOM/Document.h>
  24. #include <LibWeb/DOM/DocumentFragment.h>
  25. #include <LibWeb/DOM/DocumentType.h>
  26. #include <LibWeb/DOM/Element.h>
  27. #include <LibWeb/DOM/ElementFactory.h>
  28. #include <LibWeb/DOM/Event.h>
  29. #include <LibWeb/DOM/HTMLCollection.h>
  30. #include <LibWeb/DOM/NodeIterator.h>
  31. #include <LibWeb/DOM/ProcessingInstruction.h>
  32. #include <LibWeb/DOM/Range.h>
  33. #include <LibWeb/DOM/ShadowRoot.h>
  34. #include <LibWeb/DOM/Text.h>
  35. #include <LibWeb/DOM/TreeWalker.h>
  36. #include <LibWeb/Dump.h>
  37. #include <LibWeb/HTML/AttributeNames.h>
  38. #include <LibWeb/HTML/BrowsingContext.h>
  39. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  40. #include <LibWeb/HTML/EventNames.h>
  41. #include <LibWeb/HTML/HTMLAnchorElement.h>
  42. #include <LibWeb/HTML/HTMLAreaElement.h>
  43. #include <LibWeb/HTML/HTMLBaseElement.h>
  44. #include <LibWeb/HTML/HTMLBodyElement.h>
  45. #include <LibWeb/HTML/HTMLEmbedElement.h>
  46. #include <LibWeb/HTML/HTMLFormElement.h>
  47. #include <LibWeb/HTML/HTMLFrameSetElement.h>
  48. #include <LibWeb/HTML/HTMLHeadElement.h>
  49. #include <LibWeb/HTML/HTMLHtmlElement.h>
  50. #include <LibWeb/HTML/HTMLIFrameElement.h>
  51. #include <LibWeb/HTML/HTMLImageElement.h>
  52. #include <LibWeb/HTML/HTMLLinkElement.h>
  53. #include <LibWeb/HTML/HTMLScriptElement.h>
  54. #include <LibWeb/HTML/HTMLTitleElement.h>
  55. #include <LibWeb/HTML/Location.h>
  56. #include <LibWeb/HTML/MessageEvent.h>
  57. #include <LibWeb/HTML/NavigationParams.h>
  58. #include <LibWeb/HTML/Origin.h>
  59. #include <LibWeb/HTML/Parser/HTMLParser.h>
  60. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  61. #include <LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.h>
  62. #include <LibWeb/HTML/Window.h>
  63. #include <LibWeb/HTML/WindowProxy.h>
  64. #include <LibWeb/HighResolutionTime/TimeOrigin.h>
  65. #include <LibWeb/Infra/Strings.h>
  66. #include <LibWeb/Layout/BlockFormattingContext.h>
  67. #include <LibWeb/Layout/TreeBuilder.h>
  68. #include <LibWeb/Layout/Viewport.h>
  69. #include <LibWeb/Namespace.h>
  70. #include <LibWeb/Page/Page.h>
  71. #include <LibWeb/Platform/Timer.h>
  72. #include <LibWeb/SVG/TagNames.h>
  73. #include <LibWeb/Selection/Selection.h>
  74. #include <LibWeb/UIEvents/EventNames.h>
  75. #include <LibWeb/UIEvents/FocusEvent.h>
  76. #include <LibWeb/UIEvents/KeyboardEvent.h>
  77. #include <LibWeb/UIEvents/MouseEvent.h>
  78. #include <LibWeb/WebIDL/DOMException.h>
  79. #include <LibWeb/WebIDL/ExceptionOr.h>
  80. namespace Web::DOM {
  81. // https://html.spec.whatwg.org/multipage/origin.html#obtain-browsing-context-navigation
  82. static JS::NonnullGCPtr<HTML::BrowsingContext> obtain_a_browsing_context_to_use_for_a_navigation_response(
  83. HTML::BrowsingContext& browsing_context,
  84. HTML::SandboxingFlagSet sandbox_flags,
  85. HTML::CrossOriginOpenerPolicy navigation_coop,
  86. HTML::CrossOriginOpenerPolicyEnforcementResult coop_enforcement_result)
  87. {
  88. // 1. If browsingContext is not a top-level browsing context, return browsingContext.
  89. if (!browsing_context.is_top_level())
  90. return browsing_context;
  91. // 2. If coopEnforcementResult's needs a browsing context group switch is false, then:
  92. if (!coop_enforcement_result.needs_a_browsing_context_group_switch) {
  93. // 1. If coopEnforcementResult's would need a browsing context group switch due to report-only is true,
  94. if (coop_enforcement_result.would_need_a_browsing_context_group_switch_due_to_report_only) {
  95. // FIXME: set browsing context's virtual browsing context group ID to a new unique identifier.
  96. }
  97. // 2. Return browsingContext.
  98. return browsing_context;
  99. }
  100. // 3. Let newBrowsingContext be the result of creating a new top-level browsing context.
  101. VERIFY(browsing_context.page());
  102. auto new_browsing_context = HTML::BrowsingContext::create_a_new_top_level_browsing_context(*browsing_context.page());
  103. // FIXME: 4. If navigationCOOP's value is "same-origin-plurs-COEP", then set newBrowsingContext's group's
  104. // cross-origin isolation mode to either "logical" or "concrete". The choice of which is implementation-defined.
  105. // 5. If sandboxFlags is not empty, then:
  106. if (!sandbox_flags.is_empty()) {
  107. // 1. Assert navigationCOOP's value is "unsafe-none".
  108. VERIFY(navigation_coop.value == HTML::CrossOriginOpenerPolicyValue::UnsafeNone);
  109. // 2. Assert: newBrowsingContext's popup sandboxing flag set is empty.
  110. // 3. Set newBrowsingContext's popup sandboxing flag set to a clone of sandboxFlags.
  111. }
  112. // 6. Discard browsingContext.
  113. browsing_context.discard();
  114. // 7. Return newBrowsingContext.
  115. return new_browsing_context;
  116. }
  117. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#initialise-the-document-object
  118. WebIDL::ExceptionOr<JS::NonnullGCPtr<Document>> Document::create_and_initialize(Type type, DeprecatedString content_type, HTML::NavigationParams navigation_params)
  119. {
  120. // 1. Let browsingContext be the result of the obtaining a browsing context to use for a navigation response
  121. // given navigationParams's browsing context, navigationParams's final sandboxing flag set,
  122. // navigationParams's cross-origin opener policy, and navigationParams's COOP enforcement result.
  123. auto browsing_context = obtain_a_browsing_context_to_use_for_a_navigation_response(
  124. *navigation_params.browsing_context,
  125. navigation_params.final_sandboxing_flag_set,
  126. navigation_params.cross_origin_opener_policy,
  127. navigation_params.coop_enforcement_result);
  128. // FIXME: 2. Let permissionsPolicy be the result of creating a permissions policy from a response
  129. // given browsingContext, navigationParams's origin, and navigationParams's response.
  130. // 3. Let creationURL be navigationParams's response's URL.
  131. auto creation_url = navigation_params.response->url();
  132. // 4. If navigationParams's request is non-null, then set creationURL to navigationParams's request's current URL.
  133. if (navigation_params.request) {
  134. creation_url = navigation_params.request->current_url();
  135. }
  136. JS::GCPtr<HTML::Window> window;
  137. // 5. If browsingContext is still on its initial about:blank Document,
  138. // and navigationParams's history handling is "replace",
  139. // and browsingContext's active document's origin is same origin-domain with navigationParams's origin,
  140. // then do nothing.
  141. if (browsing_context->still_on_its_initial_about_blank_document()
  142. && navigation_params.history_handling == HTML::HistoryHandlingBehavior::Replace
  143. && (browsing_context->active_document() && browsing_context->active_document()->origin().is_same_origin(navigation_params.origin))) {
  144. // Do nothing.
  145. // NOTE: This means that both the initial about:blank Document, and the new Document that is about to be created, will share the same Window object.
  146. window = browsing_context->active_window();
  147. }
  148. // 6. Otherwise:
  149. else {
  150. // FIXME: 1. Let oacHeader be the result of getting a structured field value given `Origin-Agent-Cluster` and "item" from response's header list.
  151. // FIXME: 2. Let requestsOAC be true if oacHeader is not null and oacHeader[0] is the boolean true; otherwise false.
  152. [[maybe_unused]] auto requests_oac = false;
  153. // FIXME: 3. If navigationParams's reserved environment is a non-secure context, then set requestsOAC to false.
  154. // FIXME: 4. Let agent be the result of obtaining a similar-origin window agent given navigationParams's origin, browsingContext's group, and requestsOAC.
  155. // 5. Let realm execution context be the result of creating a new JavaScript realm given agent and the following customizations:
  156. auto realm_execution_context = Bindings::create_a_new_javascript_realm(
  157. Bindings::main_thread_vm(),
  158. [&](JS::Realm& realm) -> JS::Object* {
  159. // - For the global object, create a new Window object.
  160. window = HTML::Window::create(realm).release_value_but_fixme_should_propagate_errors();
  161. return window;
  162. },
  163. [&](JS::Realm&) -> JS::Object* {
  164. // - For the global this binding, use browsingContext's WindowProxy object.
  165. return browsing_context->window_proxy();
  166. });
  167. // 6. Let topLevelCreationURL be creationURL.
  168. auto top_level_creation_url = creation_url;
  169. // 7. Let topLevelOrigin be navigationParams's origin.
  170. auto top_level_origin = navigation_params.origin;
  171. // 8. If browsingContext is not a top-level browsing context, then:
  172. if (!browsing_context->is_top_level()) {
  173. // 1. Let parentEnvironment be browsingContext's container's relevant settings object.
  174. VERIFY(browsing_context->container());
  175. auto& parent_environment = HTML::relevant_settings_object(*browsing_context->container());
  176. // 2. Set topLevelCreationURL to parentEnvironment's top-level creation URL.
  177. top_level_creation_url = parent_environment.top_level_creation_url;
  178. // 3. Set topLevelOrigin to parentEnvironment's top-level origin.
  179. top_level_origin = parent_environment.top_level_origin;
  180. }
  181. // 9. Set up a window environment settings object with creationURL, realm execution context,
  182. // navigationParams's reserved environment, topLevelCreationURL, and topLevelOrigin.
  183. // FIXME: Why do we assume `creation_url` is non-empty here? Is this a spec bug?
  184. // FIXME: Why do we assume `top_level_creation_url` is non-empty here? Is this a spec bug?
  185. TRY(HTML::WindowEnvironmentSettingsObject::setup(
  186. creation_url.value(),
  187. move(realm_execution_context),
  188. navigation_params.reserved_environment,
  189. top_level_creation_url.value(),
  190. top_level_origin));
  191. }
  192. // FIXME: 7. Let loadTimingInfo be a new document load timing info with its navigation start time set to response's timing info's start time.
  193. // 8. Let document be a new Document,
  194. // whose type is type,
  195. // content type is contentType,
  196. // origin is navigationParams's origin,
  197. // policy container is navigationParams's policy container,
  198. // FIXME: permissions policy is permissionsPolicy,
  199. // active sandboxing flag set is navigationParams's final sandboxing flag set,
  200. // FIXME: and cross-origin opener policy is navigationParams's cross-origin opener policy,
  201. // FIXME: load timing info is loadTimingInfo,
  202. // and navigation id is navigationParams's id.
  203. auto document = TRY(Document::create(window->realm()));
  204. document->m_type = type;
  205. document->m_content_type = move(content_type);
  206. document->set_origin(navigation_params.origin);
  207. document->m_policy_container = navigation_params.policy_container;
  208. document->m_active_sandboxing_flag_set = navigation_params.final_sandboxing_flag_set;
  209. document->m_navigation_id = navigation_params.id;
  210. document->m_window = window;
  211. window->set_associated_document(*document);
  212. // 9. Set document's URL to creationURL.
  213. document->m_url = creation_url.value();
  214. // 10. Set document's current document readiness to "loading".
  215. document->m_readiness = HTML::DocumentReadyState::Loading;
  216. // FIXME: 11. Run CSP initialization for a Document given document.
  217. // 12. If navigationParams's request is non-null, then:
  218. if (navigation_params.request) {
  219. // 1. Set document's referrer to the empty string.
  220. document->m_referrer = DeprecatedString::empty();
  221. // 2. Let referrer be navigationParams's request's referrer.
  222. auto& referrer = navigation_params.request->referrer();
  223. // 3. If referrer is a URL record, then set document's referrer to the serialization of referrer.
  224. if (referrer.has<AK::URL>()) {
  225. document->m_referrer = referrer.get<AK::URL>().serialize();
  226. }
  227. }
  228. // FIXME: 13. Let historyHandling be navigationParams's history handling.
  229. // FIXME: 14: Let navigationTimingType be the result of switching on navigationParams's history handling...
  230. // FIXME: 15. Let redirectCount be 0 if navigationParams's has cross-origin redirects is true;
  231. // otherwise navigationParams's request's redirect count.
  232. // FIXME: 16. Create the navigation timing entry for document, with navigationParams's response's timing info,
  233. // redirectCount, navigationTimingType, and navigationParams's response's service worker timing info.
  234. // FIXME: 17. If navigationParams's response has a `Refresh` header, then...
  235. // FIXME: 18. If navigationParams's commit early hints is not null, then call navigationParams's commit early hints with document.
  236. // FIXME: 19. Process link headers given document, navigationParams's response, and "pre-media".
  237. // 20. Return document.
  238. return document;
  239. }
  240. WebIDL::ExceptionOr<JS::NonnullGCPtr<Document>> Document::construct_impl(JS::Realm& realm)
  241. {
  242. return Document::create(realm);
  243. }
  244. WebIDL::ExceptionOr<JS::NonnullGCPtr<Document>> Document::create(JS::Realm& realm, AK::URL const& url)
  245. {
  246. return MUST_OR_THROW_OOM(realm.heap().allocate<Document>(realm, realm, url));
  247. }
  248. Document::Document(JS::Realm& realm, const AK::URL& url)
  249. : ParentNode(realm, *this, NodeType::DOCUMENT_NODE)
  250. , m_style_computer(make<CSS::StyleComputer>(*this))
  251. , m_url(url)
  252. {
  253. HTML::main_thread_event_loop().register_document({}, *this);
  254. m_style_update_timer = Platform::Timer::create_single_shot(0, [this] {
  255. update_style();
  256. });
  257. m_layout_update_timer = Platform::Timer::create_single_shot(0, [this] {
  258. force_layout();
  259. });
  260. }
  261. Document::~Document()
  262. {
  263. HTML::main_thread_event_loop().unregister_document({}, *this);
  264. }
  265. JS::ThrowCompletionOr<void> Document::initialize(JS::Realm& realm)
  266. {
  267. MUST_OR_THROW_OOM(Base::initialize(realm));
  268. set_prototype(&Bindings::ensure_web_prototype<Bindings::DocumentPrototype>(realm, "Document"));
  269. m_selection = MUST_OR_THROW_OOM(heap().allocate<Selection::Selection>(realm, realm, *this));
  270. return {};
  271. }
  272. void Document::visit_edges(Cell::Visitor& visitor)
  273. {
  274. Base::visit_edges(visitor);
  275. visitor.visit(m_window.ptr());
  276. visitor.visit(m_style_sheets.ptr());
  277. visitor.visit(m_hovered_node.ptr());
  278. visitor.visit(m_inspected_node.ptr());
  279. visitor.visit(m_active_favicon.ptr());
  280. visitor.visit(m_focused_element.ptr());
  281. visitor.visit(m_active_element.ptr());
  282. visitor.visit(m_implementation.ptr());
  283. visitor.visit(m_current_script.ptr());
  284. visitor.visit(m_associated_inert_template_document.ptr());
  285. visitor.visit(m_appropriate_template_contents_owner_document);
  286. visitor.visit(m_pending_parsing_blocking_script.ptr());
  287. visitor.visit(m_history.ptr());
  288. visitor.visit(m_browsing_context);
  289. visitor.visit(m_applets);
  290. visitor.visit(m_anchors);
  291. visitor.visit(m_images);
  292. visitor.visit(m_embeds);
  293. visitor.visit(m_links);
  294. visitor.visit(m_forms);
  295. visitor.visit(m_scripts);
  296. visitor.visit(m_all);
  297. visitor.visit(m_selection);
  298. visitor.visit(m_first_base_element_with_href_in_tree_order);
  299. visitor.visit(m_parser);
  300. for (auto& script : m_scripts_to_execute_when_parsing_has_finished)
  301. visitor.visit(script.ptr());
  302. for (auto& script : m_scripts_to_execute_as_soon_as_possible)
  303. visitor.visit(script.ptr());
  304. for (auto& node_iterator : m_node_iterators)
  305. visitor.visit(node_iterator);
  306. for (auto& target : m_pending_scroll_event_targets)
  307. visitor.visit(target.ptr());
  308. for (auto& target : m_pending_scrollend_event_targets)
  309. visitor.visit(target.ptr());
  310. }
  311. // https://w3c.github.io/selection-api/#dom-document-getselection
  312. JS::GCPtr<Selection::Selection> Document::get_selection() const
  313. {
  314. // The method must return the selection associated with this if this has an associated browsing context,
  315. // and it must return null otherwise.
  316. if (!browsing_context())
  317. return {};
  318. return m_selection;
  319. }
  320. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-write
  321. WebIDL::ExceptionOr<void> Document::write(Vector<DeprecatedString> const& strings)
  322. {
  323. StringBuilder builder;
  324. builder.join(""sv, strings);
  325. return run_the_document_write_steps(builder.to_deprecated_string());
  326. }
  327. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-writeln
  328. WebIDL::ExceptionOr<void> Document::writeln(Vector<DeprecatedString> const& strings)
  329. {
  330. StringBuilder builder;
  331. builder.join(""sv, strings);
  332. builder.append("\n"sv);
  333. return run_the_document_write_steps(builder.to_deprecated_string());
  334. }
  335. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#document-write-steps
  336. WebIDL::ExceptionOr<void> Document::run_the_document_write_steps(DeprecatedString input)
  337. {
  338. // 1. If document is an XML document, then throw an "InvalidStateError" DOMException.
  339. if (m_type == Type::XML)
  340. return WebIDL::InvalidStateError::create(realm(), "write() called on XML document.");
  341. // 2. If document's throw-on-dynamic-markup-insertion counter is greater than 0, then throw an "InvalidStateError" DOMException.
  342. if (m_throw_on_dynamic_markup_insertion_counter > 0)
  343. return WebIDL::InvalidStateError::create(realm(), "throw-on-dynamic-markup-insertion-counter greater than zero.");
  344. // 3. If document's active parser was aborted is true, then return.
  345. if (m_active_parser_was_aborted)
  346. return {};
  347. // 4. If the insertion point is undefined, then:
  348. if (!(m_parser && m_parser->tokenizer().is_insertion_point_defined())) {
  349. // 1. If document's unload counter is greater than 0 or document's ignore-destructive-writes counter is greater than 0, then return.
  350. if (m_unload_counter > 0 || m_ignore_destructive_writes_counter > 0)
  351. return {};
  352. // 2. Run the document open steps with document.
  353. TRY(open());
  354. }
  355. // 5. Insert input into the input stream just before the insertion point.
  356. m_parser->tokenizer().insert_input_at_insertion_point(input);
  357. // 6. If there is no pending parsing-blocking script, have the HTML parser process input, one code point at a time, processing resulting tokens as they are emitted, and stopping when the tokenizer reaches the insertion point or when the processing of the tokenizer is aborted by the tree construction stage (this can happen if a script end tag token is emitted by the tokenizer).
  358. if (!pending_parsing_blocking_script())
  359. m_parser->run();
  360. return {};
  361. }
  362. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-open
  363. WebIDL::ExceptionOr<Document*> Document::open(DeprecatedString const&, DeprecatedString const&)
  364. {
  365. // 1. If document is an XML document, then throw an "InvalidStateError" DOMException exception.
  366. if (m_type == Type::XML)
  367. return WebIDL::InvalidStateError::create(realm(), "open() called on XML document.");
  368. // 2. If document's throw-on-dynamic-markup-insertion counter is greater than 0, then throw an "InvalidStateError" DOMException.
  369. if (m_throw_on_dynamic_markup_insertion_counter > 0)
  370. return WebIDL::InvalidStateError::create(realm(), "throw-on-dynamic-markup-insertion-counter greater than zero.");
  371. // FIXME: 3. Let entryDocument be the entry global object's associated Document.
  372. auto& entry_document = *this;
  373. // 4. If document's origin is not same origin to entryDocument's origin, then throw a "SecurityError" DOMException.
  374. if (origin() != entry_document.origin())
  375. return WebIDL::SecurityError::create(realm(), "Document.origin() not the same as entryDocument's.");
  376. // 5. If document has an active parser whose script nesting level is greater than 0, then return document.
  377. if (m_parser && m_parser->script_nesting_level() > 0)
  378. return this;
  379. // 6. Similarly, if document's unload counter is greater than 0, then return document.
  380. if (m_unload_counter > 0)
  381. return this;
  382. // 7. If document's active parser was aborted is true, then return document.
  383. if (m_active_parser_was_aborted)
  384. return this;
  385. // 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.
  386. // FIXME: 9. For each shadow-including inclusive descendant node of document, erase all event listeners and handlers given node.
  387. // 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.
  388. // 11. Replace all with null within document, without firing any mutation events.
  389. replace_all(nullptr);
  390. // 12. If document is fully active, then:
  391. if (is_fully_active()) {
  392. // 1. Let newURL be a copy of entryDocument's URL.
  393. auto new_url = entry_document.url();
  394. // 2. If entryDocument is not document, then set newURL's fragment to null.
  395. if (&entry_document != this)
  396. new_url.set_fragment("");
  397. // FIXME: 3. Run the URL and history update steps with document and newURL.
  398. }
  399. // 13. Set document's is initial about:blank to false.
  400. set_is_initial_about_blank(false);
  401. // FIXME: 14. If document's iframe load in progress flag is set, then set document's mute iframe load flag.
  402. // 15. Set document to no-quirks mode.
  403. set_quirks_mode(QuirksMode::No);
  404. // 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.
  405. m_parser = HTML::HTMLParser::create_for_scripting(*this);
  406. // 17. Set the insertion point to point at just before the end of the input stream (which at this point will be empty).
  407. m_parser->tokenizer().update_insertion_point();
  408. // 18. Update the current document readiness of document to "loading".
  409. update_readiness(HTML::DocumentReadyState::Loading);
  410. // 19. Return document.
  411. return this;
  412. }
  413. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-open-window
  414. WebIDL::ExceptionOr<JS::GCPtr<HTML::WindowProxy>> Document::open(DeprecatedString const& url, DeprecatedString const& name, DeprecatedString const& features)
  415. {
  416. // 1. If this is not fully active, then throw an "InvalidAccessError" DOMException exception.
  417. if (!is_fully_active())
  418. return WebIDL::InvalidAccessError::create(realm(), "Cannot perform open on a document that isn't fully active."sv);
  419. // 2. Return the result of running the window open steps with url, name, and features.
  420. return window().open_impl(url, name, features);
  421. }
  422. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#closing-the-input-stream
  423. WebIDL::ExceptionOr<void> Document::close()
  424. {
  425. // 1. If document is an XML document, then throw an "InvalidStateError" DOMException exception.
  426. if (m_type == Type::XML)
  427. return WebIDL::InvalidStateError::create(realm(), "close() called on XML document.");
  428. // 2. If document's throw-on-dynamic-markup-insertion counter is greater than 0, then throw an "InvalidStateError" DOMException.
  429. if (m_throw_on_dynamic_markup_insertion_counter > 0)
  430. return WebIDL::InvalidStateError::create(realm(), "throw-on-dynamic-markup-insertion-counter greater than zero.");
  431. // 3. If there is no script-created parser associated with the document, then return.
  432. if (!m_parser)
  433. return {};
  434. // FIXME: 4. Insert an explicit "EOF" character at the end of the parser's input stream.
  435. m_parser->tokenizer().insert_eof();
  436. // 5. If there is a pending parsing-blocking script, then return.
  437. if (pending_parsing_blocking_script())
  438. return {};
  439. // FIXME: 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.
  440. m_parser->run();
  441. return {};
  442. }
  443. HTML::Origin Document::origin() const
  444. {
  445. return m_origin;
  446. }
  447. void Document::set_origin(HTML::Origin const& origin)
  448. {
  449. m_origin = origin;
  450. }
  451. void Document::schedule_style_update()
  452. {
  453. if (m_style_update_timer->is_active())
  454. return;
  455. m_style_update_timer->start();
  456. }
  457. void Document::schedule_layout_update()
  458. {
  459. if (m_layout_update_timer->is_active())
  460. return;
  461. m_layout_update_timer->start();
  462. }
  463. bool Document::is_child_allowed(Node const& node) const
  464. {
  465. switch (node.type()) {
  466. case NodeType::DOCUMENT_NODE:
  467. case NodeType::TEXT_NODE:
  468. return false;
  469. case NodeType::COMMENT_NODE:
  470. return true;
  471. case NodeType::DOCUMENT_TYPE_NODE:
  472. return !first_child_of_type<DocumentType>();
  473. case NodeType::ELEMENT_NODE:
  474. return !first_child_of_type<Element>();
  475. default:
  476. return false;
  477. }
  478. }
  479. Element* Document::document_element()
  480. {
  481. return first_child_of_type<Element>();
  482. }
  483. Element const* Document::document_element() const
  484. {
  485. return first_child_of_type<Element>();
  486. }
  487. HTML::HTMLHtmlElement* Document::html_element()
  488. {
  489. auto* html = document_element();
  490. if (is<HTML::HTMLHtmlElement>(html))
  491. return verify_cast<HTML::HTMLHtmlElement>(html);
  492. return nullptr;
  493. }
  494. HTML::HTMLHeadElement* Document::head()
  495. {
  496. auto* html = html_element();
  497. if (!html)
  498. return nullptr;
  499. return html->first_child_of_type<HTML::HTMLHeadElement>();
  500. }
  501. HTML::HTMLElement* Document::body()
  502. {
  503. auto* html = html_element();
  504. if (!html)
  505. return nullptr;
  506. auto* first_body = html->first_child_of_type<HTML::HTMLBodyElement>();
  507. if (first_body)
  508. return first_body;
  509. auto* first_frameset = html->first_child_of_type<HTML::HTMLFrameSetElement>();
  510. if (first_frameset)
  511. return first_frameset;
  512. return nullptr;
  513. }
  514. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-body
  515. WebIDL::ExceptionOr<void> Document::set_body(HTML::HTMLElement* new_body)
  516. {
  517. if (!is<HTML::HTMLBodyElement>(new_body) && !is<HTML::HTMLFrameSetElement>(new_body))
  518. return WebIDL::HierarchyRequestError::create(realm(), "Invalid document body element, must be 'body' or 'frameset'");
  519. auto* existing_body = body();
  520. if (existing_body) {
  521. (void)TRY(existing_body->parent()->replace_child(*new_body, *existing_body));
  522. return {};
  523. }
  524. auto* document_element = this->document_element();
  525. if (!document_element)
  526. return WebIDL::HierarchyRequestError::create(realm(), "Missing document element");
  527. (void)TRY(document_element->append_child(*new_body));
  528. return {};
  529. }
  530. DeprecatedString Document::title() const
  531. {
  532. auto* head_element = head();
  533. if (!head_element)
  534. return {};
  535. auto* title_element = head_element->first_child_of_type<HTML::HTMLTitleElement>();
  536. if (!title_element)
  537. return {};
  538. auto raw_title = title_element->text_content();
  539. StringBuilder builder;
  540. bool last_was_space = false;
  541. for (auto code_point : Utf8View(raw_title)) {
  542. if (is_ascii_space(code_point)) {
  543. last_was_space = true;
  544. } else {
  545. if (last_was_space && !builder.is_empty())
  546. builder.append(' ');
  547. builder.append_code_point(code_point);
  548. last_was_space = false;
  549. }
  550. }
  551. return builder.to_deprecated_string();
  552. }
  553. void Document::set_title(DeprecatedString const& title)
  554. {
  555. auto* head_element = const_cast<HTML::HTMLHeadElement*>(head());
  556. if (!head_element)
  557. return;
  558. JS::GCPtr<HTML::HTMLTitleElement> title_element = head_element->first_child_of_type<HTML::HTMLTitleElement>();
  559. if (!title_element) {
  560. title_element = &static_cast<HTML::HTMLTitleElement&>(*create_element(HTML::TagNames::title).release_value());
  561. MUST(head_element->append_child(*title_element));
  562. }
  563. title_element->remove_all_children(true);
  564. MUST(title_element->append_child(heap().allocate<Text>(realm(), *this, title).release_allocated_value_but_fixme_should_propagate_errors()));
  565. if (auto* page = this->page()) {
  566. if (browsing_context() == &page->top_level_browsing_context())
  567. page->client().page_did_change_title(title);
  568. }
  569. }
  570. void Document::tear_down_layout_tree()
  571. {
  572. if (!m_layout_root)
  573. return;
  574. // Gather up all the layout nodes in a vector and detach them from parents
  575. // while the vector keeps them alive.
  576. Vector<JS::Handle<Layout::Node>> layout_nodes;
  577. m_layout_root->for_each_in_inclusive_subtree([&](auto& layout_node) {
  578. layout_nodes.append(layout_node);
  579. return IterationDecision::Continue;
  580. });
  581. for (auto& layout_node : layout_nodes) {
  582. if (layout_node->parent())
  583. layout_node->parent()->remove_child(*layout_node);
  584. }
  585. m_layout_root = nullptr;
  586. }
  587. Color Document::background_color(Gfx::Palette const& palette) const
  588. {
  589. // CSS2 says we should use the HTML element's background color unless it's transparent...
  590. if (auto* html_element = this->html_element(); html_element && html_element->layout_node()) {
  591. auto color = html_element->layout_node()->computed_values().background_color();
  592. if (color.alpha())
  593. return color;
  594. }
  595. // ...in which case we use the BODY element's background color.
  596. if (auto* body_element = body(); body_element && body_element->layout_node()) {
  597. auto color = body_element->layout_node()->computed_values().background_color();
  598. if (color.alpha())
  599. return color;
  600. }
  601. // If both HTML and BODY are transparent, we fall back to the system's "base" palette color.
  602. return palette.base();
  603. }
  604. Vector<CSS::BackgroundLayerData> const* Document::background_layers() const
  605. {
  606. auto* body_element = body();
  607. if (!body_element)
  608. return {};
  609. auto* body_layout_node = body_element->layout_node();
  610. if (!body_layout_node)
  611. return {};
  612. return &body_layout_node->background_layers();
  613. }
  614. void Document::update_base_element(Badge<HTML::HTMLBaseElement>)
  615. {
  616. JS::GCPtr<HTML::HTMLBaseElement const> base_element;
  617. for_each_in_subtree_of_type<HTML::HTMLBaseElement>([&base_element](HTML::HTMLBaseElement const& base_element_in_tree) {
  618. if (base_element_in_tree.has_attribute(HTML::AttributeNames::href)) {
  619. base_element = &base_element_in_tree;
  620. return IterationDecision::Break;
  621. }
  622. return IterationDecision::Continue;
  623. });
  624. m_first_base_element_with_href_in_tree_order = base_element;
  625. }
  626. JS::GCPtr<HTML::HTMLBaseElement const> Document::first_base_element_with_href_in_tree_order() const
  627. {
  628. return m_first_base_element_with_href_in_tree_order;
  629. }
  630. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#fallback-base-url
  631. AK::URL Document::fallback_base_url() const
  632. {
  633. // FIXME: 1. If document is an iframe srcdoc document, then return the document base URL of document's browsing context's container document.
  634. // 2. If document's URL is about:blank, and document's browsing context's creator base URL is non-null, then return that creator base URL.
  635. if (m_url == "about:blank"sv && browsing_context() && browsing_context()->creator_url().has_value())
  636. return browsing_context()->creator_url().value();
  637. // 3. Return document's URL.
  638. return m_url;
  639. }
  640. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#document-base-url
  641. AK::URL Document::base_url() const
  642. {
  643. // 1. If there is no base element that has an href attribute in the Document, then return the Document's fallback base URL.
  644. auto base_element = first_base_element_with_href_in_tree_order();
  645. if (!base_element)
  646. return fallback_base_url();
  647. // 2. Otherwise, return the frozen base URL of the first base element in the Document that has an href attribute, in tree order.
  648. return base_element->frozen_base_url();
  649. }
  650. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#parse-a-url
  651. AK::URL Document::parse_url(DeprecatedString const& url) const
  652. {
  653. // FIXME: Pass in document's character encoding.
  654. return base_url().complete_url(url);
  655. }
  656. void Document::set_needs_layout()
  657. {
  658. if (m_needs_layout)
  659. return;
  660. m_needs_layout = true;
  661. schedule_layout_update();
  662. }
  663. void Document::force_layout()
  664. {
  665. tear_down_layout_tree();
  666. update_layout();
  667. }
  668. void Document::invalidate_layout()
  669. {
  670. tear_down_layout_tree();
  671. schedule_layout_update();
  672. }
  673. void Document::update_layout()
  674. {
  675. // NOTE: If our parent document needs a relayout, we must do that *first*.
  676. // This is necessary as the parent layout may cause our viewport to change.
  677. if (browsing_context() && browsing_context()->container())
  678. browsing_context()->container()->document().update_layout();
  679. update_style();
  680. if (!m_needs_layout && m_layout_root)
  681. return;
  682. // NOTE: If this is a document hosting <template> contents, layout is unnecessary.
  683. if (m_created_for_appropriate_template_contents)
  684. return;
  685. if (!browsing_context())
  686. return;
  687. auto viewport_rect = browsing_context()->viewport_rect();
  688. if (!m_layout_root) {
  689. m_next_layout_node_serial_id = 0;
  690. Layout::TreeBuilder tree_builder;
  691. m_layout_root = verify_cast<Layout::Viewport>(*tree_builder.build(*this));
  692. }
  693. Layout::LayoutState layout_state;
  694. layout_state.used_values_per_layout_node.resize(layout_node_count());
  695. {
  696. Layout::BlockFormattingContext root_formatting_context(layout_state, *m_layout_root, nullptr);
  697. auto& viewport = static_cast<Layout::Viewport&>(*m_layout_root);
  698. auto& viewport_state = layout_state.get_mutable(viewport);
  699. viewport_state.set_content_width(viewport_rect.width());
  700. viewport_state.set_content_height(viewport_rect.height());
  701. root_formatting_context.run(
  702. *m_layout_root,
  703. Layout::LayoutMode::Normal,
  704. Layout::AvailableSpace(
  705. Layout::AvailableSize::make_definite(viewport_rect.width()),
  706. Layout::AvailableSize::make_definite(viewport_rect.height())));
  707. }
  708. layout_state.commit();
  709. browsing_context()->set_needs_display();
  710. if (browsing_context()->is_top_level() && browsing_context()->active_document() == this) {
  711. if (auto* page = this->page())
  712. page->client().page_did_layout();
  713. }
  714. m_layout_root->recompute_selection_states();
  715. m_needs_layout = false;
  716. m_layout_update_timer->stop();
  717. }
  718. [[nodiscard]] static bool update_style_recursively(DOM::Node& node)
  719. {
  720. bool const needs_full_style_update = node.document().needs_full_style_update();
  721. bool needs_relayout = false;
  722. if (is<Element>(node)) {
  723. needs_relayout |= static_cast<Element&>(node).recompute_style() == Element::NeedsRelayout::Yes;
  724. }
  725. node.set_needs_style_update(false);
  726. if (needs_full_style_update || node.child_needs_style_update()) {
  727. if (node.is_element()) {
  728. if (auto* shadow_root = static_cast<DOM::Element&>(node).shadow_root_internal()) {
  729. if (needs_full_style_update || shadow_root->needs_style_update() || shadow_root->child_needs_style_update())
  730. needs_relayout |= update_style_recursively(*shadow_root);
  731. }
  732. }
  733. node.for_each_child([&](auto& child) {
  734. if (needs_full_style_update || child.needs_style_update() || child.child_needs_style_update())
  735. needs_relayout |= update_style_recursively(child);
  736. return IterationDecision::Continue;
  737. });
  738. }
  739. node.set_child_needs_style_update(false);
  740. return needs_relayout;
  741. }
  742. void Document::update_style()
  743. {
  744. if (!browsing_context())
  745. return;
  746. if (!needs_full_style_update() && !needs_style_update() && !child_needs_style_update())
  747. return;
  748. // NOTE: If this is a document hosting <template> contents, style update is unnecessary.
  749. if (m_created_for_appropriate_template_contents)
  750. return;
  751. evaluate_media_rules();
  752. if (update_style_recursively(*this))
  753. invalidate_layout();
  754. m_needs_full_style_update = false;
  755. m_style_update_timer->stop();
  756. }
  757. void Document::set_link_color(Color color)
  758. {
  759. m_link_color = color;
  760. }
  761. void Document::set_active_link_color(Color color)
  762. {
  763. m_active_link_color = color;
  764. }
  765. void Document::set_visited_link_color(Color color)
  766. {
  767. m_visited_link_color = color;
  768. }
  769. Layout::Viewport const* Document::layout_node() const
  770. {
  771. return static_cast<Layout::Viewport const*>(Node::layout_node());
  772. }
  773. Layout::Viewport* Document::layout_node()
  774. {
  775. return static_cast<Layout::Viewport*>(Node::layout_node());
  776. }
  777. void Document::set_inspected_node(Node* node)
  778. {
  779. if (m_inspected_node.ptr() == node)
  780. return;
  781. if (m_inspected_node && m_inspected_node->layout_node())
  782. m_inspected_node->layout_node()->set_needs_display();
  783. m_inspected_node = node;
  784. if (m_inspected_node && m_inspected_node->layout_node())
  785. m_inspected_node->layout_node()->set_needs_display();
  786. }
  787. static Node* find_common_ancestor(Node* a, Node* b)
  788. {
  789. if (!a || !b)
  790. return nullptr;
  791. if (a == b)
  792. return a;
  793. HashTable<Node*> ancestors;
  794. for (auto* node = a; node; node = node->parent_or_shadow_host())
  795. ancestors.set(node);
  796. for (auto* node = b; node; node = node->parent_or_shadow_host()) {
  797. if (ancestors.contains(node))
  798. return node;
  799. }
  800. return nullptr;
  801. }
  802. void Document::set_hovered_node(Node* node)
  803. {
  804. if (m_hovered_node.ptr() == node)
  805. return;
  806. JS::GCPtr<Node> old_hovered_node = move(m_hovered_node);
  807. m_hovered_node = node;
  808. auto* common_ancestor = find_common_ancestor(old_hovered_node, m_hovered_node);
  809. if (common_ancestor)
  810. common_ancestor->invalidate_style();
  811. else
  812. invalidate_style();
  813. // https://w3c.github.io/uievents/#mouseleave
  814. if (old_hovered_node && (!m_hovered_node || !m_hovered_node->is_descendant_of(*old_hovered_node))) {
  815. // FIXME: Check if we need to dispatch these events in a specific order.
  816. for (auto target = old_hovered_node; target && target.ptr() != common_ancestor; target = target->parent()) {
  817. // FIXME: Populate the event with mouse coordinates, etc.
  818. target->dispatch_event(UIEvents::MouseEvent::create(realm(), UIEvents::EventNames::mouseleave).release_value_but_fixme_should_propagate_errors());
  819. }
  820. }
  821. // https://w3c.github.io/uievents/#mouseenter
  822. if (m_hovered_node && (!old_hovered_node || !m_hovered_node->is_ancestor_of(*old_hovered_node))) {
  823. // FIXME: Check if we need to dispatch these events in a specific order.
  824. for (auto target = m_hovered_node; target && target.ptr() != common_ancestor; target = target->parent()) {
  825. // FIXME: Populate the event with mouse coordinates, etc.
  826. target->dispatch_event(UIEvents::MouseEvent::create(realm(), UIEvents::EventNames::mouseenter).release_value_but_fixme_should_propagate_errors());
  827. }
  828. }
  829. }
  830. JS::NonnullGCPtr<HTMLCollection> Document::get_elements_by_name(DeprecatedString const& name)
  831. {
  832. return HTMLCollection::create(*this, [name](Element const& element) {
  833. return element.name() == name;
  834. }).release_value_but_fixme_should_propagate_errors();
  835. }
  836. JS::NonnullGCPtr<HTMLCollection> Document::get_elements_by_class_name(DeprecatedFlyString const& class_names)
  837. {
  838. Vector<FlyString> list_of_class_names;
  839. for (auto& name : class_names.view().split_view(' ')) {
  840. list_of_class_names.append(FlyString::from_utf8(name).release_value_but_fixme_should_propagate_errors());
  841. }
  842. return HTMLCollection::create(*this, [list_of_class_names = move(list_of_class_names), quirks_mode = document().in_quirks_mode()](Element const& element) {
  843. for (auto& name : list_of_class_names) {
  844. if (!element.has_class(name, quirks_mode ? CaseSensitivity::CaseInsensitive : CaseSensitivity::CaseSensitive))
  845. return false;
  846. }
  847. return true;
  848. }).release_value_but_fixme_should_propagate_errors();
  849. }
  850. // https://html.spec.whatwg.org/multipage/obsolete.html#dom-document-applets
  851. JS::NonnullGCPtr<HTMLCollection> Document::applets()
  852. {
  853. if (!m_applets)
  854. m_applets = HTMLCollection::create(*this, [](auto&) { return false; }).release_value_but_fixme_should_propagate_errors();
  855. return *m_applets;
  856. }
  857. // https://html.spec.whatwg.org/multipage/obsolete.html#dom-document-anchors
  858. JS::NonnullGCPtr<HTMLCollection> Document::anchors()
  859. {
  860. if (!m_anchors) {
  861. m_anchors = HTMLCollection::create(*this, [](Element const& element) {
  862. return is<HTML::HTMLAnchorElement>(element) && element.has_attribute(HTML::AttributeNames::name);
  863. }).release_value_but_fixme_should_propagate_errors();
  864. }
  865. return *m_anchors;
  866. }
  867. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-images
  868. JS::NonnullGCPtr<HTMLCollection> Document::images()
  869. {
  870. if (!m_images) {
  871. m_images = HTMLCollection::create(*this, [](Element const& element) {
  872. return is<HTML::HTMLImageElement>(element);
  873. }).release_value_but_fixme_should_propagate_errors();
  874. }
  875. return *m_images;
  876. }
  877. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-embeds
  878. JS::NonnullGCPtr<HTMLCollection> Document::embeds()
  879. {
  880. if (!m_embeds) {
  881. m_embeds = HTMLCollection::create(*this, [](Element const& element) {
  882. return is<HTML::HTMLEmbedElement>(element);
  883. }).release_value_but_fixme_should_propagate_errors();
  884. }
  885. return *m_embeds;
  886. }
  887. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-plugins
  888. JS::NonnullGCPtr<HTMLCollection> Document::plugins()
  889. {
  890. return embeds();
  891. }
  892. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-links
  893. JS::NonnullGCPtr<HTMLCollection> Document::links()
  894. {
  895. if (!m_links) {
  896. m_links = HTMLCollection::create(*this, [](Element const& element) {
  897. return (is<HTML::HTMLAnchorElement>(element) || is<HTML::HTMLAreaElement>(element)) && element.has_attribute(HTML::AttributeNames::href);
  898. }).release_value_but_fixme_should_propagate_errors();
  899. }
  900. return *m_links;
  901. }
  902. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-forms
  903. JS::NonnullGCPtr<HTMLCollection> Document::forms()
  904. {
  905. if (!m_forms) {
  906. m_forms = HTMLCollection::create(*this, [](Element const& element) {
  907. return is<HTML::HTMLFormElement>(element);
  908. }).release_value_but_fixme_should_propagate_errors();
  909. }
  910. return *m_forms;
  911. }
  912. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-scripts
  913. JS::NonnullGCPtr<HTMLCollection> Document::scripts()
  914. {
  915. if (!m_scripts) {
  916. m_scripts = HTMLCollection::create(*this, [](Element const& element) {
  917. return is<HTML::HTMLScriptElement>(element);
  918. }).release_value_but_fixme_should_propagate_errors();
  919. }
  920. return *m_scripts;
  921. }
  922. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-all
  923. JS::NonnullGCPtr<HTMLCollection> Document::all()
  924. {
  925. if (!m_all) {
  926. m_all = HTMLCollection::create(*this, [](Element const&) {
  927. return true;
  928. }).release_value_but_fixme_should_propagate_errors();
  929. }
  930. return *m_all;
  931. }
  932. Color Document::link_color() const
  933. {
  934. if (m_link_color.has_value())
  935. return m_link_color.value();
  936. if (!page())
  937. return Color::Blue;
  938. return page()->palette().link();
  939. }
  940. Color Document::active_link_color() const
  941. {
  942. if (m_active_link_color.has_value())
  943. return m_active_link_color.value();
  944. if (!page())
  945. return Color::Red;
  946. return page()->palette().active_link();
  947. }
  948. Color Document::visited_link_color() const
  949. {
  950. if (m_visited_link_color.has_value())
  951. return m_visited_link_color.value();
  952. if (!page())
  953. return Color::Magenta;
  954. return page()->palette().visited_link();
  955. }
  956. // https://html.spec.whatwg.org/multipage/webappapis.html#relevant-settings-object
  957. HTML::EnvironmentSettingsObject& Document::relevant_settings_object()
  958. {
  959. // Then, the relevant settings object for a platform object o is the environment settings object of the relevant Realm for o.
  960. return Bindings::host_defined_environment_settings_object(realm());
  961. }
  962. JS::Value Document::run_javascript(StringView source, StringView filename)
  963. {
  964. // FIXME: The only user of this function now is javascript: URLs. Refactor them to follow the spec: https://html.spec.whatwg.org/multipage/browsing-the-web.html#javascript-protocol
  965. auto interpreter = JS::Interpreter::create_with_existing_realm(realm());
  966. auto script_or_error = JS::Script::parse(source, realm(), filename);
  967. if (script_or_error.is_error()) {
  968. // FIXME: Add error logging back.
  969. return JS::js_undefined();
  970. }
  971. auto result = interpreter->run(script_or_error.value());
  972. if (result.is_error()) {
  973. // FIXME: I'm sure the spec could tell us something about error propagation here!
  974. HTML::report_exception(result, realm());
  975. return {};
  976. }
  977. return result.value();
  978. }
  979. // https://dom.spec.whatwg.org/#dom-document-createelement
  980. WebIDL::ExceptionOr<JS::NonnullGCPtr<Element>> Document::create_element(DeprecatedFlyString const& a_local_name)
  981. {
  982. auto local_name = a_local_name;
  983. // 1. If localName does not match the Name production, then throw an "InvalidCharacterError" DOMException.
  984. if (!is_valid_name(local_name))
  985. return WebIDL::InvalidCharacterError::create(realm(), "Invalid character in tag name.");
  986. // 2. If this is an HTML document, then set localName to localName in ASCII lowercase.
  987. if (document_type() == Type::HTML)
  988. local_name = local_name.to_lowercase();
  989. // FIXME: 3. Let is be null.
  990. // FIXME: 4. If options is a dictionary and options["is"] exists, then set is to it.
  991. // 5. Let namespace be the HTML namespace, if this is an HTML document or this’s content type is "application/xhtml+xml"; otherwise null.
  992. DeprecatedFlyString namespace_;
  993. if (document_type() == Type::HTML || content_type() == "application/xhtml+xml"sv)
  994. namespace_ = Namespace::HTML;
  995. // 6. Return the result of creating an element given this, localName, namespace, null, is, and with the synchronous custom elements flag set.
  996. return TRY(DOM::create_element(*this, local_name, namespace_));
  997. }
  998. // https://dom.spec.whatwg.org/#dom-document-createelementns
  999. // https://dom.spec.whatwg.org/#internal-createelementns-steps
  1000. // FIXME: This only implements step 4 of the algorithm and does not take in options.
  1001. WebIDL::ExceptionOr<JS::NonnullGCPtr<Element>> Document::create_element_ns(DeprecatedString const& namespace_, DeprecatedString const& qualified_name)
  1002. {
  1003. // 1. Let namespace, prefix, and localName be the result of passing namespace and qualifiedName to validate and extract.
  1004. auto extracted_qualified_name = TRY(validate_and_extract(realm(), namespace_, qualified_name));
  1005. // FIXME: 2. Let is be null.
  1006. // FIXME: 3. If options is a dictionary and options["is"] exists, then set is to it.
  1007. // 4. Return the result of creating an element given document, localName, namespace, prefix, is, and with the synchronous custom elements flag set.
  1008. return TRY(DOM::create_element(*this, extracted_qualified_name.local_name(), extracted_qualified_name.namespace_(), extracted_qualified_name.prefix()));
  1009. }
  1010. JS::NonnullGCPtr<DocumentFragment> Document::create_document_fragment()
  1011. {
  1012. return heap().allocate<DocumentFragment>(realm(), *this).release_allocated_value_but_fixme_should_propagate_errors();
  1013. }
  1014. JS::NonnullGCPtr<Text> Document::create_text_node(DeprecatedString const& data)
  1015. {
  1016. return heap().allocate<Text>(realm(), *this, data).release_allocated_value_but_fixme_should_propagate_errors();
  1017. }
  1018. JS::NonnullGCPtr<Comment> Document::create_comment(DeprecatedString const& data)
  1019. {
  1020. return heap().allocate<Comment>(realm(), *this, data).release_allocated_value_but_fixme_should_propagate_errors();
  1021. }
  1022. // https://dom.spec.whatwg.org/#dom-document-createprocessinginstruction
  1023. WebIDL::ExceptionOr<JS::NonnullGCPtr<ProcessingInstruction>> Document::create_processing_instruction(DeprecatedString const& target, DeprecatedString const& data)
  1024. {
  1025. // FIXME: 1. If target does not match the Name production, then throw an "InvalidCharacterError" DOMException.
  1026. // FIXME: 2. If data contains the string "?>", then throw an "InvalidCharacterError" DOMException.
  1027. // 3. Return a new ProcessingInstruction node, with target set to target, data set to data, and node document set to this.
  1028. return MUST_OR_THROW_OOM(heap().allocate<ProcessingInstruction>(realm(), *this, data, target));
  1029. }
  1030. JS::NonnullGCPtr<Range> Document::create_range()
  1031. {
  1032. return Range::create(*this).release_value_but_fixme_should_propagate_errors();
  1033. }
  1034. // https://dom.spec.whatwg.org/#dom-document-createevent
  1035. WebIDL::ExceptionOr<JS::NonnullGCPtr<Event>> Document::create_event(DeprecatedString const& interface)
  1036. {
  1037. auto& realm = this->realm();
  1038. // NOTE: This is named event here, since we do step 5 and 6 as soon as possible for each case.
  1039. // 1. Let constructor be null.
  1040. JS::GCPtr<Event> event;
  1041. // 2. If interface is an ASCII case-insensitive match for any of the strings in the first column in the following table,
  1042. // then set constructor to the interface in the second column on the same row as the matching string:
  1043. if (Infra::is_ascii_case_insensitive_match(interface, "beforeunloadevent"sv)) {
  1044. event = TRY(Event::create(realm, "")); // FIXME: Create BeforeUnloadEvent
  1045. } else if (Infra::is_ascii_case_insensitive_match(interface, "compositionevent"sv)) {
  1046. event = TRY(Event::create(realm, "")); // FIXME: Create CompositionEvent
  1047. } else if (Infra::is_ascii_case_insensitive_match(interface, "customevent"sv)) {
  1048. event = TRY(CustomEvent::create(realm, ""));
  1049. } else if (Infra::is_ascii_case_insensitive_match(interface, "devicemotionevent"sv)) {
  1050. event = TRY(Event::create(realm, "")); // FIXME: Create DeviceMotionEvent
  1051. } else if (Infra::is_ascii_case_insensitive_match(interface, "deviceorientationevent"sv)) {
  1052. event = TRY(Event::create(realm, "")); // FIXME: Create DeviceOrientationEvent
  1053. } else if (Infra::is_ascii_case_insensitive_match(interface, "dragevent"sv)) {
  1054. event = TRY(Event::create(realm, "")); // FIXME: Create DragEvent
  1055. } else if (Infra::is_ascii_case_insensitive_match(interface, "event"sv)
  1056. || Infra::is_ascii_case_insensitive_match(interface, "events"sv)) {
  1057. event = TRY(Event::create(realm, ""));
  1058. } else if (Infra::is_ascii_case_insensitive_match(interface, "focusevent"sv)) {
  1059. event = TRY(UIEvents::FocusEvent::create(realm, ""));
  1060. } else if (Infra::is_ascii_case_insensitive_match(interface, "hashchangeevent"sv)) {
  1061. event = TRY(Event::create(realm, "")); // FIXME: Create HashChangeEvent
  1062. } else if (Infra::is_ascii_case_insensitive_match(interface, "htmlevents"sv)) {
  1063. event = TRY(Event::create(realm, ""));
  1064. } else if (Infra::is_ascii_case_insensitive_match(interface, "keyboardevent"sv)) {
  1065. event = TRY(UIEvents::KeyboardEvent::create(realm, ""));
  1066. } else if (Infra::is_ascii_case_insensitive_match(interface, "messageevent"sv)) {
  1067. event = TRY(HTML::MessageEvent::create(realm, String {}));
  1068. } else if (Infra::is_ascii_case_insensitive_match(interface, "mouseevent"sv)
  1069. || Infra::is_ascii_case_insensitive_match(interface, "mouseevents"sv)) {
  1070. event = TRY(UIEvents::MouseEvent::create(realm, ""));
  1071. } else if (Infra::is_ascii_case_insensitive_match(interface, "storageevent"sv)) {
  1072. event = TRY(Event::create(realm, "")); // FIXME: Create StorageEvent
  1073. } else if (Infra::is_ascii_case_insensitive_match(interface, "svgevents"sv)) {
  1074. event = TRY(Event::create(realm, ""));
  1075. } else if (Infra::is_ascii_case_insensitive_match(interface, "textevent"sv)) {
  1076. event = TRY(Event::create(realm, "")); // FIXME: Create CompositionEvent
  1077. } else if (Infra::is_ascii_case_insensitive_match(interface, "touchevent"sv)) {
  1078. event = TRY(Event::create(realm, "")); // FIXME: Create TouchEvent
  1079. } else if (Infra::is_ascii_case_insensitive_match(interface, "uievent"sv)
  1080. || Infra::is_ascii_case_insensitive_match(interface, "uievents"sv)) {
  1081. event = TRY(UIEvents::UIEvent::create(realm, ""));
  1082. }
  1083. // 3. If constructor is null, then throw a "NotSupportedError" DOMException.
  1084. if (!event) {
  1085. return WebIDL::NotSupportedError::create(realm, "No constructor for interface found");
  1086. }
  1087. // FIXME: 4. If the interface indicated by constructor is not exposed on the relevant global object of this, then throw a "NotSupportedError" DOMException.
  1088. // NOTE: These are done in the if-chain above
  1089. // 5. Let event be the result of creating an event given constructor.
  1090. // 6. Initialize event’s type attribute to the empty string.
  1091. // NOTE: This is handled by each constructor.
  1092. // FIXME: 7. Initialize event’s timeStamp attribute to the result of calling current high resolution time with this’s relevant global object.
  1093. // 8. Initialize event’s isTrusted attribute to false.
  1094. event->set_is_trusted(false);
  1095. // 9. Unset event’s initialized flag.
  1096. event->set_initialized(false);
  1097. // 10. Return event.
  1098. return JS::NonnullGCPtr(*event);
  1099. }
  1100. void Document::set_pending_parsing_blocking_script(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement* script)
  1101. {
  1102. m_pending_parsing_blocking_script = script;
  1103. }
  1104. JS::NonnullGCPtr<HTML::HTMLScriptElement> Document::take_pending_parsing_blocking_script(Badge<HTML::HTMLParser>)
  1105. {
  1106. VERIFY(m_pending_parsing_blocking_script);
  1107. auto script = m_pending_parsing_blocking_script;
  1108. m_pending_parsing_blocking_script = nullptr;
  1109. return *script;
  1110. }
  1111. void Document::add_script_to_execute_when_parsing_has_finished(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement& script)
  1112. {
  1113. m_scripts_to_execute_when_parsing_has_finished.append(JS::make_handle(script));
  1114. }
  1115. Vector<JS::Handle<HTML::HTMLScriptElement>> Document::take_scripts_to_execute_when_parsing_has_finished(Badge<HTML::HTMLParser>)
  1116. {
  1117. return move(m_scripts_to_execute_when_parsing_has_finished);
  1118. }
  1119. void Document::add_script_to_execute_as_soon_as_possible(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement& script)
  1120. {
  1121. m_scripts_to_execute_as_soon_as_possible.append(JS::make_handle(script));
  1122. }
  1123. Vector<JS::Handle<HTML::HTMLScriptElement>> Document::take_scripts_to_execute_as_soon_as_possible(Badge<HTML::HTMLParser>)
  1124. {
  1125. return move(m_scripts_to_execute_as_soon_as_possible);
  1126. }
  1127. void Document::add_script_to_execute_in_order_as_soon_as_possible(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement& script)
  1128. {
  1129. m_scripts_to_execute_in_order_as_soon_as_possible.append(JS::make_handle(script));
  1130. }
  1131. Vector<JS::Handle<HTML::HTMLScriptElement>> Document::take_scripts_to_execute_in_order_as_soon_as_possible(Badge<HTML::HTMLParser>)
  1132. {
  1133. return move(m_scripts_to_execute_in_order_as_soon_as_possible);
  1134. }
  1135. // https://dom.spec.whatwg.org/#dom-document-importnode
  1136. WebIDL::ExceptionOr<JS::NonnullGCPtr<Node>> Document::import_node(JS::NonnullGCPtr<Node> node, bool deep)
  1137. {
  1138. // 1. If node is a document or shadow root, then throw a "NotSupportedError" DOMException.
  1139. if (is<Document>(*node) || is<ShadowRoot>(*node))
  1140. return WebIDL::NotSupportedError::create(realm(), "Cannot import a document or shadow root.");
  1141. // 2. Return a clone of node, with this and the clone children flag set if deep is true.
  1142. return node->clone_node(this, deep);
  1143. }
  1144. // https://dom.spec.whatwg.org/#concept-node-adopt
  1145. void Document::adopt_node(Node& node)
  1146. {
  1147. auto& old_document = node.document();
  1148. if (node.parent())
  1149. node.remove();
  1150. if (&old_document != this) {
  1151. node.for_each_shadow_including_descendant([&](auto& inclusive_descendant) {
  1152. inclusive_descendant.set_document({}, *this);
  1153. // FIXME: If inclusiveDescendant is an element, then set the node document of each attribute in inclusiveDescendant’s attribute list to document.
  1154. return IterationDecision::Continue;
  1155. });
  1156. // FIXME: For each inclusiveDescendant in node’s shadow-including inclusive descendants that is custom,
  1157. // enqueue a custom element callback reaction with inclusiveDescendant, callback name "adoptedCallback",
  1158. // and an argument list containing oldDocument and document.
  1159. node.for_each_shadow_including_descendant([&](auto& inclusive_descendant) {
  1160. inclusive_descendant.adopted_from(old_document);
  1161. return IterationDecision::Continue;
  1162. });
  1163. // Transfer NodeIterators rooted at `node` from old_document to this document.
  1164. Vector<NodeIterator&> node_iterators_to_transfer;
  1165. for (auto node_iterator : old_document.m_node_iterators) {
  1166. if (node_iterator->root().ptr() == &node)
  1167. node_iterators_to_transfer.append(*node_iterator);
  1168. }
  1169. for (auto& node_iterator : node_iterators_to_transfer) {
  1170. old_document.m_node_iterators.remove(&node_iterator);
  1171. m_node_iterators.set(&node_iterator);
  1172. }
  1173. }
  1174. }
  1175. // https://dom.spec.whatwg.org/#dom-document-adoptnode
  1176. WebIDL::ExceptionOr<JS::NonnullGCPtr<Node>> Document::adopt_node_binding(JS::NonnullGCPtr<Node> node)
  1177. {
  1178. if (is<Document>(*node))
  1179. return WebIDL::NotSupportedError::create(realm(), "Cannot adopt a document into a document");
  1180. if (is<ShadowRoot>(*node))
  1181. return WebIDL::HierarchyRequestError::create(realm(), "Cannot adopt a shadow root into a document");
  1182. if (is<DocumentFragment>(*node) && verify_cast<DocumentFragment>(*node).host())
  1183. return node;
  1184. adopt_node(*node);
  1185. return node;
  1186. }
  1187. DocumentType const* Document::doctype() const
  1188. {
  1189. return first_child_of_type<DocumentType>();
  1190. }
  1191. DeprecatedString const& Document::compat_mode() const
  1192. {
  1193. static DeprecatedString back_compat = "BackCompat";
  1194. static DeprecatedString css1_compat = "CSS1Compat";
  1195. if (m_quirks_mode == QuirksMode::Yes)
  1196. return back_compat;
  1197. return css1_compat;
  1198. }
  1199. bool Document::is_editable() const
  1200. {
  1201. return m_editable;
  1202. }
  1203. void Document::set_focused_element(Element* element)
  1204. {
  1205. if (m_focused_element.ptr() == element)
  1206. return;
  1207. if (m_focused_element) {
  1208. m_focused_element->did_lose_focus();
  1209. m_focused_element->set_needs_style_update(true);
  1210. }
  1211. m_focused_element = element;
  1212. if (m_focused_element) {
  1213. m_focused_element->did_receive_focus();
  1214. m_focused_element->set_needs_style_update(true);
  1215. }
  1216. if (m_layout_root)
  1217. m_layout_root->set_needs_display();
  1218. // Scroll the viewport if necessary to make the newly focused element visible.
  1219. if (m_focused_element)
  1220. (void)m_focused_element->scroll_into_view();
  1221. }
  1222. void Document::set_active_element(Element* element)
  1223. {
  1224. if (m_active_element.ptr() == element)
  1225. return;
  1226. m_active_element = element;
  1227. if (m_layout_root)
  1228. m_layout_root->set_needs_display();
  1229. }
  1230. DeprecatedString Document::ready_state() const
  1231. {
  1232. switch (m_readiness) {
  1233. case HTML::DocumentReadyState::Loading:
  1234. return "loading"sv;
  1235. case HTML::DocumentReadyState::Interactive:
  1236. return "interactive"sv;
  1237. case HTML::DocumentReadyState::Complete:
  1238. return "complete"sv;
  1239. }
  1240. VERIFY_NOT_REACHED();
  1241. }
  1242. // https://html.spec.whatwg.org/multipage/dom.html#update-the-current-document-readiness
  1243. void Document::update_readiness(HTML::DocumentReadyState readiness_value)
  1244. {
  1245. // 1. If document's current document readiness equals readinessValue, then return.
  1246. if (m_readiness == readiness_value)
  1247. return;
  1248. // 2. Set document's current document readiness to readinessValue.
  1249. m_readiness = readiness_value;
  1250. // 3. If document is associated with an HTML parser, then:
  1251. if (m_parser) {
  1252. // 1. Let now be the current high resolution time given document's relevant global object.
  1253. auto now = HighResolutionTime::unsafe_shared_current_time();
  1254. // 2. If readinessValue is "complete", and document's load timing info's DOM complete time is 0,
  1255. // then set document's load timing info's DOM complete time to now.
  1256. if (readiness_value == HTML::DocumentReadyState::Complete && m_load_timing_info.dom_complete_time == 0) {
  1257. m_load_timing_info.dom_complete_time = now;
  1258. }
  1259. // 3. Otherwise, if readinessValue is "interactive", and document's load timing info's DOM interactive time is 0,
  1260. // then set document's load timing info's DOM interactive time to now.
  1261. else if (readiness_value == HTML::DocumentReadyState::Interactive && m_load_timing_info.dom_interactive_time == 0) {
  1262. m_load_timing_info.dom_interactive_time = now;
  1263. }
  1264. }
  1265. // 4. Fire an event named readystatechange at document.
  1266. dispatch_event(Event::create(realm(), HTML::EventNames::readystatechange).release_value_but_fixme_should_propagate_errors());
  1267. }
  1268. Page* Document::page()
  1269. {
  1270. return m_browsing_context ? m_browsing_context->page() : nullptr;
  1271. }
  1272. Page const* Document::page() const
  1273. {
  1274. return m_browsing_context ? m_browsing_context->page() : nullptr;
  1275. }
  1276. EventTarget* Document::get_parent(Event const& event)
  1277. {
  1278. if (event.type() == HTML::EventNames::load)
  1279. return nullptr;
  1280. return m_window;
  1281. }
  1282. // https://html.spec.whatwg.org/#completely-loaded
  1283. bool Document::is_completely_loaded() const
  1284. {
  1285. return m_completely_loaded_time.has_value();
  1286. }
  1287. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#completely-finish-loading
  1288. void Document::completely_finish_loading()
  1289. {
  1290. // 1. Assert: document's browsing context is non-null.
  1291. VERIFY(browsing_context());
  1292. // 2. Set document's completely loaded time to the current time.
  1293. m_completely_loaded_time = AK::Time::now_realtime();
  1294. // 3. Let container be document's browsing context's container.
  1295. auto container = JS::make_handle(browsing_context()->container());
  1296. // 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.
  1297. if (container && is<HTML::HTMLIFrameElement>(*container)) {
  1298. container->queue_an_element_task(HTML::Task::Source::DOMManipulation, [container] {
  1299. run_iframe_load_event_steps(static_cast<HTML::HTMLIFrameElement&>(*container));
  1300. });
  1301. }
  1302. // 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.
  1303. else if (container) {
  1304. container->queue_an_element_task(HTML::Task::Source::DOMManipulation, [container] {
  1305. container->dispatch_event(DOM::Event::create(container->realm(), HTML::EventNames::load).release_value_but_fixme_should_propagate_errors());
  1306. });
  1307. }
  1308. }
  1309. DeprecatedString Document::cookie(Cookie::Source source)
  1310. {
  1311. if (auto* page = this->page())
  1312. return page->client().page_did_request_cookie(m_url, source);
  1313. return {};
  1314. }
  1315. void Document::set_cookie(DeprecatedString const& cookie_string, Cookie::Source source)
  1316. {
  1317. auto cookie = Cookie::parse_cookie(cookie_string);
  1318. if (!cookie.has_value())
  1319. return;
  1320. if (auto* page = this->page())
  1321. page->client().page_did_set_cookie(m_url, cookie.value(), source);
  1322. }
  1323. DeprecatedString Document::dump_dom_tree_as_json() const
  1324. {
  1325. StringBuilder builder;
  1326. auto json = MUST(JsonObjectSerializer<>::try_create(builder));
  1327. serialize_tree_as_json(json);
  1328. MUST(json.finish());
  1329. return builder.to_deprecated_string();
  1330. }
  1331. // https://html.spec.whatwg.org/multipage/semantics.html#has-a-style-sheet-that-is-blocking-scripts
  1332. bool Document::has_a_style_sheet_that_is_blocking_scripts() const
  1333. {
  1334. // A Document has a style sheet that is blocking scripts if its script-blocking style sheet counter is greater than 0,
  1335. if (m_script_blocking_style_sheet_counter > 0)
  1336. return true;
  1337. // ...or if that Document has a non-null browsing context whose container document is non-null and has a script-blocking style sheet counter greater than 0.
  1338. if (!browsing_context() || !browsing_context()->container_document())
  1339. return false;
  1340. return browsing_context()->container_document()->m_script_blocking_style_sheet_counter > 0;
  1341. }
  1342. DeprecatedString Document::referrer() const
  1343. {
  1344. return m_referrer;
  1345. }
  1346. void Document::set_referrer(DeprecatedString referrer)
  1347. {
  1348. m_referrer = referrer;
  1349. }
  1350. // https://html.spec.whatwg.org/multipage/browsers.html#fully-active
  1351. bool Document::is_fully_active() const
  1352. {
  1353. // A Document d is said to be fully active when d's browsing context is non-null, d's browsing context's active document is d,
  1354. // and either d's browsing context is a top-level browsing context, or d's browsing context's container document is fully active.
  1355. auto* browsing_context = this->browsing_context();
  1356. if (!browsing_context)
  1357. return false;
  1358. if (browsing_context->active_document() != this)
  1359. return false;
  1360. if (browsing_context->is_top_level())
  1361. return true;
  1362. if (auto* browsing_context_container_document = browsing_context->container_document()) {
  1363. if (browsing_context_container_document->is_fully_active())
  1364. return true;
  1365. }
  1366. return false;
  1367. }
  1368. // https://html.spec.whatwg.org/multipage/browsers.html#active-document
  1369. bool Document::is_active() const
  1370. {
  1371. // A browsing context's active document is its active window's associated Document.
  1372. return browsing_context() && browsing_context()->active_document() == this;
  1373. }
  1374. // https://html.spec.whatwg.org/multipage/history.html#dom-document-location
  1375. WebIDL::ExceptionOr<JS::GCPtr<HTML::Location>> Document::location()
  1376. {
  1377. // The Document object's location attribute's getter must return this Document object's relevant global object's Location object,
  1378. // if this Document object is fully active, and null otherwise.
  1379. if (!is_fully_active())
  1380. return nullptr;
  1381. return TRY(window().location());
  1382. }
  1383. // https://html.spec.whatwg.org/multipage/interaction.html#dom-document-hidden
  1384. bool Document::hidden() const
  1385. {
  1386. return visibility_state() == "hidden";
  1387. }
  1388. // https://html.spec.whatwg.org/multipage/interaction.html#dom-document-visibilitystate
  1389. DeprecatedString Document::visibility_state() const
  1390. {
  1391. switch (m_visibility_state) {
  1392. case HTML::VisibilityState::Hidden:
  1393. return "hidden"sv;
  1394. case HTML::VisibilityState::Visible:
  1395. return "visible"sv;
  1396. }
  1397. VERIFY_NOT_REACHED();
  1398. }
  1399. void Document::set_visibility_state(Badge<HTML::BrowsingContext>, HTML::VisibilityState visibility_state)
  1400. {
  1401. m_visibility_state = visibility_state;
  1402. }
  1403. // https://html.spec.whatwg.org/multipage/interaction.html#update-the-visibility-state
  1404. void Document::update_the_visibility_state(HTML::VisibilityState visibility_state)
  1405. {
  1406. // 1. If document's visibility state equals visibilityState, then return.
  1407. if (m_visibility_state == visibility_state)
  1408. return;
  1409. // 2. Set document's visibility state to visibilityState.
  1410. m_visibility_state = visibility_state;
  1411. // FIXME: 3. Run any page visibility change steps which may be defined in other specifications, with visibility state and document.
  1412. // 4. Fire an event named visibilitychange at document, with its bubbles attribute initialized to true.
  1413. auto event = DOM::Event::create(realm(), HTML::EventNames::visibilitychange).release_value_but_fixme_should_propagate_errors();
  1414. event->set_bubbles(true);
  1415. dispatch_event(event);
  1416. }
  1417. // https://drafts.csswg.org/cssom-view/#run-the-resize-steps
  1418. void Document::run_the_resize_steps()
  1419. {
  1420. // 1. If doc’s viewport has had its width or height changed
  1421. // (e.g. as a result of the user resizing the browser window, or changing the page zoom scale factor,
  1422. // or an iframe element’s dimensions are changed) since the last time these steps were run,
  1423. // fire an event named resize at the Window object associated with doc.
  1424. if (!browsing_context())
  1425. return;
  1426. auto viewport_size = browsing_context()->viewport_rect().size().to_type<float>().to_type<int>();
  1427. if (m_last_viewport_size == viewport_size)
  1428. return;
  1429. m_last_viewport_size = viewport_size;
  1430. window().dispatch_event(DOM::Event::create(realm(), UIEvents::EventNames::resize).release_value_but_fixme_should_propagate_errors());
  1431. schedule_layout_update();
  1432. }
  1433. // https://w3c.github.io/csswg-drafts/cssom-view-1/#document-run-the-scroll-steps
  1434. void Document::run_the_scroll_steps()
  1435. {
  1436. // 1. For each item target in doc’s pending scroll event targets, in the order they were added to the list, run these substeps:
  1437. for (auto& target : m_pending_scroll_event_targets) {
  1438. // 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.
  1439. if (is<Document>(*target)) {
  1440. auto event = DOM::Event::create(realm(), HTML::EventNames::scroll).release_value_but_fixme_should_propagate_errors();
  1441. event->set_bubbles(true);
  1442. target->dispatch_event(event);
  1443. // FIXME: Fire at the associated VisualViewport
  1444. }
  1445. // 2. Otherwise, fire an event named scroll at target.
  1446. else {
  1447. auto event = DOM::Event::create(realm(), HTML::EventNames::scroll).release_value_but_fixme_should_propagate_errors();
  1448. target->dispatch_event(event);
  1449. }
  1450. }
  1451. // 2. Empty doc’s pending scroll event targets.
  1452. m_pending_scroll_event_targets.clear();
  1453. }
  1454. void Document::add_media_query_list(JS::NonnullGCPtr<CSS::MediaQueryList> media_query_list)
  1455. {
  1456. m_media_query_lists.append(*media_query_list);
  1457. }
  1458. // https://drafts.csswg.org/cssom-view/#evaluate-media-queries-and-report-changes
  1459. void Document::evaluate_media_queries_and_report_changes()
  1460. {
  1461. // NOTE: Not in the spec, but we take this opportunity to prune null WeakPtrs.
  1462. m_media_query_lists.remove_all_matching([](auto& it) {
  1463. return it.is_null();
  1464. });
  1465. // 1. For each MediaQueryList object target that has doc as its document,
  1466. // in the order they were created, oldest first, run these substeps:
  1467. for (auto& media_query_list_ptr : m_media_query_lists) {
  1468. // 1. If target’s matches state has changed since the last time these steps
  1469. // were run, fire an event at target using the MediaQueryListEvent constructor,
  1470. // with its type attribute initialized to change, its isTrusted attribute
  1471. // initialized to true, its media attribute initialized to target’s media,
  1472. // and its matches attribute initialized to target’s matches state.
  1473. if (media_query_list_ptr.is_null())
  1474. continue;
  1475. JS::GCPtr<CSS::MediaQueryList> media_query_list = media_query_list_ptr.ptr();
  1476. bool did_match = media_query_list->matches();
  1477. bool now_matches = media_query_list->evaluate();
  1478. if (did_match != now_matches) {
  1479. CSS::MediaQueryListEventInit init;
  1480. init.media = String::from_deprecated_string(media_query_list->media()).release_value_but_fixme_should_propagate_errors();
  1481. init.matches = now_matches;
  1482. auto event = CSS::MediaQueryListEvent::create(realm(), HTML::EventNames::change, init).release_value_but_fixme_should_propagate_errors();
  1483. event->set_is_trusted(true);
  1484. media_query_list->dispatch_event(*event);
  1485. }
  1486. }
  1487. // Also not in the spec, but this is as good a place as any to evaluate @media rules!
  1488. evaluate_media_rules();
  1489. }
  1490. void Document::evaluate_media_rules()
  1491. {
  1492. bool any_media_queries_changed_match_state = false;
  1493. for (auto& style_sheet : style_sheets().sheets()) {
  1494. if (style_sheet->evaluate_media_queries(window()))
  1495. any_media_queries_changed_match_state = true;
  1496. }
  1497. if (any_media_queries_changed_match_state) {
  1498. style_computer().invalidate_rule_cache();
  1499. invalidate_style();
  1500. }
  1501. }
  1502. DOMImplementation* Document::implementation()
  1503. {
  1504. if (!m_implementation)
  1505. m_implementation = DOMImplementation::create(*this).release_value_but_fixme_should_propagate_errors();
  1506. return m_implementation;
  1507. }
  1508. bool Document::has_focus() const
  1509. {
  1510. // FIXME: Return whether we actually have focus.
  1511. return true;
  1512. }
  1513. void Document::set_parser(Badge<HTML::HTMLParser>, HTML::HTMLParser& parser)
  1514. {
  1515. m_parser = parser;
  1516. }
  1517. void Document::detach_parser(Badge<HTML::HTMLParser>)
  1518. {
  1519. m_parser = nullptr;
  1520. }
  1521. // https://www.w3.org/TR/xml/#NT-NameStartChar
  1522. static bool is_valid_name_start_character(u32 code_point)
  1523. {
  1524. return code_point == ':'
  1525. || (code_point >= 'A' && code_point <= 'Z')
  1526. || code_point == '_'
  1527. || (code_point >= 'a' && code_point <= 'z')
  1528. || (code_point >= 0xc0 && code_point <= 0xd6)
  1529. || (code_point >= 0xd8 && code_point <= 0xf6)
  1530. || (code_point >= 0xf8 && code_point <= 0x2ff)
  1531. || (code_point >= 0x370 && code_point <= 0x37d)
  1532. || (code_point >= 0x37f && code_point <= 0x1fff)
  1533. || (code_point >= 0x200c && code_point <= 0x200d)
  1534. || (code_point >= 0x2070 && code_point <= 0x218f)
  1535. || (code_point >= 0x2c00 && code_point <= 0x2fef)
  1536. || (code_point >= 0x3001 && code_point <= 0xD7ff)
  1537. || (code_point >= 0xf900 && code_point <= 0xfdcf)
  1538. || (code_point >= 0xfdf0 && code_point <= 0xfffd)
  1539. || (code_point >= 0x10000 && code_point <= 0xeffff);
  1540. }
  1541. // https://www.w3.org/TR/xml/#NT-NameChar
  1542. static inline bool is_valid_name_character(u32 code_point)
  1543. {
  1544. return is_valid_name_start_character(code_point)
  1545. || code_point == '-'
  1546. || code_point == '.'
  1547. || (code_point >= '0' && code_point <= '9')
  1548. || code_point == 0xb7
  1549. || (code_point >= 0x300 && code_point <= 0x36f)
  1550. || (code_point >= 0x203f && code_point <= 0x2040);
  1551. }
  1552. bool Document::is_valid_name(DeprecatedString const& name)
  1553. {
  1554. if (name.is_empty())
  1555. return false;
  1556. if (!is_valid_name_start_character(name[0]))
  1557. return false;
  1558. for (size_t i = 1; i < name.length(); ++i) {
  1559. if (!is_valid_name_character(name[i]))
  1560. return false;
  1561. }
  1562. return true;
  1563. }
  1564. // https://dom.spec.whatwg.org/#validate
  1565. WebIDL::ExceptionOr<Document::PrefixAndTagName> Document::validate_qualified_name(JS::Realm& realm, DeprecatedString const& qualified_name)
  1566. {
  1567. if (qualified_name.is_empty())
  1568. return WebIDL::InvalidCharacterError::create(realm, "Empty string is not a valid qualified name.");
  1569. Utf8View utf8view { qualified_name };
  1570. if (!utf8view.validate())
  1571. return WebIDL::InvalidCharacterError::create(realm, "Invalid qualified name.");
  1572. Optional<size_t> colon_offset;
  1573. bool at_start_of_name = true;
  1574. for (auto it = utf8view.begin(); it != utf8view.end(); ++it) {
  1575. auto code_point = *it;
  1576. if (code_point == ':') {
  1577. if (colon_offset.has_value())
  1578. return WebIDL::InvalidCharacterError::create(realm, "More than one colon (:) in qualified name.");
  1579. colon_offset = utf8view.byte_offset_of(it);
  1580. at_start_of_name = true;
  1581. continue;
  1582. }
  1583. if (at_start_of_name) {
  1584. if (!is_valid_name_start_character(code_point))
  1585. return WebIDL::InvalidCharacterError::create(realm, "Invalid start of qualified name.");
  1586. at_start_of_name = false;
  1587. continue;
  1588. }
  1589. if (!is_valid_name_character(code_point))
  1590. return WebIDL::InvalidCharacterError::create(realm, "Invalid character in qualified name.");
  1591. }
  1592. if (!colon_offset.has_value())
  1593. return Document::PrefixAndTagName {
  1594. .prefix = {},
  1595. .tag_name = qualified_name,
  1596. };
  1597. if (*colon_offset == 0)
  1598. return WebIDL::InvalidCharacterError::create(realm, "Qualified name can't start with colon (:).");
  1599. if (*colon_offset >= (qualified_name.length() - 1))
  1600. return WebIDL::InvalidCharacterError::create(realm, "Qualified name can't end with colon (:).");
  1601. return Document::PrefixAndTagName {
  1602. .prefix = qualified_name.substring_view(0, *colon_offset),
  1603. .tag_name = qualified_name.substring_view(*colon_offset + 1),
  1604. };
  1605. }
  1606. // https://dom.spec.whatwg.org/#dom-document-createnodeiterator
  1607. JS::NonnullGCPtr<NodeIterator> Document::create_node_iterator(Node& root, unsigned what_to_show, JS::GCPtr<NodeFilter> filter)
  1608. {
  1609. return NodeIterator::create(root, what_to_show, filter).release_value_but_fixme_should_propagate_errors();
  1610. }
  1611. // https://dom.spec.whatwg.org/#dom-document-createtreewalker
  1612. JS::NonnullGCPtr<TreeWalker> Document::create_tree_walker(Node& root, unsigned what_to_show, JS::GCPtr<NodeFilter> filter)
  1613. {
  1614. return TreeWalker::create(root, what_to_show, filter).release_value_but_fixme_should_propagate_errors();
  1615. }
  1616. void Document::register_node_iterator(Badge<NodeIterator>, NodeIterator& node_iterator)
  1617. {
  1618. auto result = m_node_iterators.set(&node_iterator);
  1619. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  1620. }
  1621. void Document::unregister_node_iterator(Badge<NodeIterator>, NodeIterator& node_iterator)
  1622. {
  1623. bool was_removed = m_node_iterators.remove(&node_iterator);
  1624. VERIFY(was_removed);
  1625. }
  1626. void Document::increment_number_of_things_delaying_the_load_event(Badge<DocumentLoadEventDelayer>)
  1627. {
  1628. ++m_number_of_things_delaying_the_load_event;
  1629. if (auto* page = this->page())
  1630. page->client().page_did_update_resource_count(m_number_of_things_delaying_the_load_event);
  1631. }
  1632. void Document::decrement_number_of_things_delaying_the_load_event(Badge<DocumentLoadEventDelayer>)
  1633. {
  1634. VERIFY(m_number_of_things_delaying_the_load_event);
  1635. --m_number_of_things_delaying_the_load_event;
  1636. if (auto* page = this->page())
  1637. page->client().page_did_update_resource_count(m_number_of_things_delaying_the_load_event);
  1638. }
  1639. void Document::invalidate_stacking_context_tree()
  1640. {
  1641. if (auto* paint_box = this->paint_box())
  1642. const_cast<Painting::PaintableBox*>(paint_box)->invalidate_stacking_context();
  1643. }
  1644. void Document::check_favicon_after_loading_link_resource()
  1645. {
  1646. // https://html.spec.whatwg.org/multipage/links.html#rel-icon
  1647. // NOTE: firefox also load favicons outside the head tag, which is against spec (see table 4.6.7)
  1648. auto* head_element = head();
  1649. if (!head_element)
  1650. return;
  1651. auto favicon_link_elements = HTMLCollection::create(*head_element, [](Element const& element) {
  1652. if (!is<HTML::HTMLLinkElement>(element))
  1653. return false;
  1654. return static_cast<HTML::HTMLLinkElement const&>(element).has_loaded_icon();
  1655. }).release_value_but_fixme_should_propagate_errors();
  1656. if (favicon_link_elements->length() == 0) {
  1657. dbgln_if(SPAM_DEBUG, "No favicon found to be used");
  1658. return;
  1659. }
  1660. // 4.6.7.8 Link type "icon"
  1661. //
  1662. // If there are multiple equally appropriate icons, user agents must use the last one declared
  1663. // in tree order at the time that the user agent collected the list of icons.
  1664. //
  1665. // If multiple icons are provided, the user agent must select the most appropriate icon
  1666. // according to the type, media, and sizes attributes.
  1667. //
  1668. // FIXME: There is no selective behavior yet for favicons.
  1669. for (auto i = favicon_link_elements->length(); i-- > 0;) {
  1670. auto favicon_element = favicon_link_elements->item(i);
  1671. if (favicon_element == m_active_element.ptr())
  1672. return;
  1673. // If the user agent tries to use an icon but that icon is determined, upon closer examination,
  1674. // to in fact be inappropriate (...), then the user agent must try the next-most-appropriate icon
  1675. // as determined by the attributes.
  1676. if (static_cast<HTML::HTMLLinkElement*>(favicon_element)->load_favicon_and_use_if_window_is_active()) {
  1677. m_active_favicon = favicon_element;
  1678. return;
  1679. }
  1680. }
  1681. dbgln_if(SPAM_DEBUG, "No favicon found to be used");
  1682. }
  1683. void Document::set_window(Badge<HTML::BrowsingContext>, HTML::Window& window)
  1684. {
  1685. m_window = &window;
  1686. }
  1687. CSS::StyleSheetList& Document::style_sheets()
  1688. {
  1689. if (!m_style_sheets)
  1690. m_style_sheets = CSS::StyleSheetList::create(*this).release_value_but_fixme_should_propagate_errors();
  1691. return *m_style_sheets;
  1692. }
  1693. CSS::StyleSheetList const& Document::style_sheets() const
  1694. {
  1695. return const_cast<Document*>(this)->style_sheets();
  1696. }
  1697. JS::NonnullGCPtr<HTML::History> Document::history()
  1698. {
  1699. if (!m_history)
  1700. m_history = HTML::History::create(realm(), *this).release_value_but_fixme_should_propagate_errors();
  1701. return *m_history;
  1702. }
  1703. JS::NonnullGCPtr<HTML::History> Document::history() const
  1704. {
  1705. return const_cast<Document*>(this)->history();
  1706. }
  1707. // https://html.spec.whatwg.org/multipage/origin.html#dom-document-domain
  1708. DeprecatedString Document::domain() const
  1709. {
  1710. // 1. Let effectiveDomain be this's origin's effective domain.
  1711. auto effective_domain = origin().effective_domain();
  1712. // 2. If effectiveDomain is null, then return the empty string.
  1713. if (!effective_domain.has_value())
  1714. return DeprecatedString::empty();
  1715. // 3. Return effectiveDomain, serialized.
  1716. // FIXME: Implement host serialization.
  1717. return effective_domain.release_value();
  1718. }
  1719. void Document::set_domain(DeprecatedString const& domain)
  1720. {
  1721. dbgln("(STUBBED) Document::set_domain(domain='{}')", domain);
  1722. }
  1723. void Document::set_navigation_id(Optional<AK::DeprecatedString> navigation_id)
  1724. {
  1725. m_navigation_id = move(navigation_id);
  1726. }
  1727. Optional<DeprecatedString> Document::navigation_id() const
  1728. {
  1729. return m_navigation_id;
  1730. }
  1731. HTML::SandboxingFlagSet Document::active_sandboxing_flag_set() const
  1732. {
  1733. return m_active_sandboxing_flag_set;
  1734. }
  1735. HTML::PolicyContainer Document::policy_container() const
  1736. {
  1737. return m_policy_container;
  1738. }
  1739. // https://html.spec.whatwg.org/multipage/browsers.html#list-of-the-descendant-browsing-contexts
  1740. Vector<JS::Handle<HTML::BrowsingContext>> Document::list_of_descendant_browsing_contexts() const
  1741. {
  1742. // 1. Let list be an empty list.
  1743. Vector<JS::Handle<HTML::BrowsingContext>> list;
  1744. // 2. For each browsing context container container,
  1745. // whose nested browsing context is non-null and whose shadow-including root is d, in shadow-including tree order:
  1746. // NOTE: We already store our browsing contexts in a tree structure, so we can simply collect all the descendants
  1747. // of this document's browsing context.
  1748. if (browsing_context()) {
  1749. browsing_context()->for_each_in_subtree([&](auto& context) {
  1750. list.append(JS::make_handle(context));
  1751. return IterationDecision::Continue;
  1752. });
  1753. }
  1754. return list;
  1755. }
  1756. // https://html.spec.whatwg.org/multipage/window-object.html#discard-a-document
  1757. void Document::discard()
  1758. {
  1759. // 1. Set document's salvageable state to false.
  1760. m_salvageable = false;
  1761. // FIXME: 2. Run any unloading document cleanup steps for document that are defined by this specification and other applicable specifications.
  1762. // 3. Abort document.
  1763. abort();
  1764. // 4. Remove any tasks associated with document in any task source, without running those tasks.
  1765. HTML::main_thread_event_loop().task_queue().remove_tasks_matching([this](auto& task) {
  1766. return task.document() == this;
  1767. });
  1768. // 5. Discard all the child browsing contexts of document.
  1769. if (browsing_context()) {
  1770. browsing_context()->for_each_child([](HTML::BrowsingContext& child_browsing_context) {
  1771. child_browsing_context.discard();
  1772. });
  1773. }
  1774. // FIXME: 6. For each session history entry entry whose document is equal to document, set entry's document to null.
  1775. // 7. Set document's browsing context to null.
  1776. tear_down_layout_tree();
  1777. m_browsing_context = nullptr;
  1778. // FIXME: 8. Remove document from the owner set of each WorkerGlobalScope object whose set contains document.
  1779. // FIXME: 9. For each workletGlobalScope in document's worklet global scopes, terminate workletGlobalScope.
  1780. }
  1781. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#abort-a-document
  1782. void Document::abort()
  1783. {
  1784. // 1. Abort the active documents of every child browsing context.
  1785. // If this results in any of those Document objects having their salvageable state set to false,
  1786. // then set document's salvageable state to false also.
  1787. if (browsing_context()) {
  1788. browsing_context()->for_each_child([this](HTML::BrowsingContext& child_browsing_context) {
  1789. if (auto* child_document = child_browsing_context.active_document()) {
  1790. child_document->abort();
  1791. if (!child_document->m_salvageable)
  1792. m_salvageable = false;
  1793. }
  1794. });
  1795. }
  1796. // FIXME: 2. Cancel any instances of the fetch algorithm in the context of document,
  1797. // discarding any tasks queued for them, and discarding any further data received from the network for them.
  1798. // If this resulted in any instances of the fetch algorithm being canceled
  1799. // or any queued tasks or any network data getting discarded,
  1800. // then set document's salvageable state to false.
  1801. // 3. If document's navigation id is non-null, then:
  1802. if (m_navigation_id.has_value()) {
  1803. // 1. FIXME: Invoke WebDriver BiDi navigation aborted with document's browsing context,
  1804. // and new WebDriver BiDi navigation status whose whose id is document's navigation id,
  1805. // status is "canceled", and url is document's URL.
  1806. // 2. Set document's navigation id to null.
  1807. m_navigation_id = {};
  1808. }
  1809. // 4. If document has an active parser, then:
  1810. if (auto parser = active_parser()) {
  1811. // 1. Set document's active parser was aborted to true.
  1812. m_active_parser_was_aborted = true;
  1813. // 2. Abort that parser.
  1814. parser->abort();
  1815. // 3. Set document's salvageable state to false.
  1816. m_salvageable = false;
  1817. }
  1818. }
  1819. // https://html.spec.whatwg.org/multipage/dom.html#active-parser
  1820. JS::GCPtr<HTML::HTMLParser> Document::active_parser()
  1821. {
  1822. if (!m_parser)
  1823. return nullptr;
  1824. if (m_parser->aborted() || m_parser->stopped())
  1825. return nullptr;
  1826. return m_parser;
  1827. }
  1828. void Document::set_browsing_context(HTML::BrowsingContext* browsing_context)
  1829. {
  1830. m_browsing_context = browsing_context;
  1831. }
  1832. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#unload-a-document
  1833. void Document::unload(bool recursive_flag, Optional<DocumentUnloadTimingInfo> unload_timing_info)
  1834. {
  1835. // 1. Increase the event loop's termination nesting level by one.
  1836. HTML::main_thread_event_loop().increment_termination_nesting_level();
  1837. // 2. Increase document's unload counter by 1.
  1838. m_unload_counter += 1;
  1839. // 3. If the user agent does not intend to keep document alive in a session history entry
  1840. // (such that it can be reused later on history traversal), set document's salvageable state to false.
  1841. // FIXME: If we want to implement fast back/forward cache, this has to change.
  1842. m_salvageable = false;
  1843. // 4. If document's page showing flag is true:
  1844. if (m_page_showing) {
  1845. // 1. Set document's page showing flag to false.
  1846. m_page_showing = false;
  1847. // 2. Fire a page transition event named pagehide at document's relevant global object with document's salvageable state.
  1848. global_object().fire_a_page_transition_event(HTML::EventNames::pagehide, m_salvageable);
  1849. // 3. Update the visibility state of newDocument to "hidden".
  1850. update_the_visibility_state(HTML::VisibilityState::Hidden);
  1851. }
  1852. // 5. If unloadTimingInfo is not null,
  1853. if (unload_timing_info.has_value()) {
  1854. // then set unloadTimingInfo's unload event start time to the current high resolution time given newGlobal,
  1855. // coarsened given document's relevant settings object's cross-origin isolated capability.
  1856. unload_timing_info->unload_event_start_time = HighResolutionTime::coarsen_time(
  1857. HighResolutionTime::unsafe_shared_current_time(),
  1858. relevant_settings_object().cross_origin_isolated_capability() == HTML::CanUseCrossOriginIsolatedAPIs::Yes);
  1859. }
  1860. // 6. If document's salvageable state is false,
  1861. if (!m_salvageable) {
  1862. // then fire an event named unload at document's relevant global object, with legacy target override flag set.
  1863. // FIXME: The legacy target override flag is currently set by a virtual override of dispatch_event()
  1864. // We should reorganize this so that the flag appears explicitly here instead.
  1865. auto event = DOM::Event::create(realm(), HTML::EventNames::unload).release_value_but_fixme_should_propagate_errors();
  1866. global_object().dispatch_event(event);
  1867. }
  1868. // 7. If unloadTimingInfo is not null,
  1869. if (unload_timing_info.has_value()) {
  1870. // then set unloadTimingInfo's unload event end time to the current high resolution time given newGlobal,
  1871. // coarsened given document's relevant settings object's cross-origin isolated capability.
  1872. unload_timing_info->unload_event_end_time = HighResolutionTime::coarsen_time(
  1873. HighResolutionTime::unsafe_shared_current_time(),
  1874. relevant_settings_object().cross_origin_isolated_capability() == HTML::CanUseCrossOriginIsolatedAPIs::Yes);
  1875. }
  1876. // 8. Decrease the event loop's termination nesting level by one.
  1877. HTML::main_thread_event_loop().decrement_termination_nesting_level();
  1878. // FIXME: 9. Set document's suspension time to the current high resolution time given document's relevant global object.
  1879. // FIXME: 10. Set document's suspended timer handles to the result of getting the keys for the map of active timers.
  1880. // FIXME: 11. Run any unloading document cleanup steps for document that are defined by this specification and other applicable specifications.
  1881. // 12. If the recursiveFlag is not set, then:
  1882. if (!recursive_flag) {
  1883. // 1. Let descendants be the list of the descendant browsing contexts of document.
  1884. auto descendants = list_of_descendant_browsing_contexts();
  1885. // 2. For each browsingContext in descendants:
  1886. for (auto browsing_context : descendants) {
  1887. JS::GCPtr<Document> active_document = browsing_context->active_document();
  1888. if (!active_document)
  1889. continue;
  1890. // 1. Unload the active document of browsingContext with the recursiveFlag set.
  1891. active_document->unload(true);
  1892. // 2. If the salvageable state of the active document of browsingContext is false,
  1893. // then set the salvageable state of document to false also.
  1894. if (!active_document->m_salvageable)
  1895. m_salvageable = false;
  1896. }
  1897. // 3. If document's salvageable state is false, then discard document.
  1898. if (!m_salvageable)
  1899. discard();
  1900. }
  1901. // 13. Decrease document's unload counter by 1.
  1902. m_unload_counter -= 1;
  1903. }
  1904. void Document::did_stop_being_active_document_in_browsing_context(Badge<HTML::BrowsingContext>)
  1905. {
  1906. tear_down_layout_tree();
  1907. }
  1908. // https://w3c.github.io/editing/docs/execCommand/#querycommandsupported()
  1909. bool Document::query_command_supported(DeprecatedString const& command) const
  1910. {
  1911. dbgln("(STUBBED) Document::query_command_supported(command='{}')", command);
  1912. return false;
  1913. }
  1914. // https://html.spec.whatwg.org/multipage/scripting.html#appropriate-template-contents-owner-document
  1915. JS::NonnullGCPtr<DOM::Document> Document::appropriate_template_contents_owner_document()
  1916. {
  1917. // 1. If doc is not a Document created by this algorithm, then:
  1918. if (!created_for_appropriate_template_contents()) {
  1919. // 1. If doc does not yet have an associated inert template document, then:
  1920. if (!m_associated_inert_template_document) {
  1921. // 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.
  1922. auto new_document = DOM::Document::create(realm()).release_value_but_fixme_should_propagate_errors();
  1923. new_document->m_created_for_appropriate_template_contents = true;
  1924. // 2. If doc is an HTML document, mark new doc as an HTML document also.
  1925. if (document_type() == Type::HTML)
  1926. new_document->set_document_type(Type::HTML);
  1927. // 3. Let doc's associated inert template document be new doc.
  1928. m_associated_inert_template_document = new_document;
  1929. }
  1930. // 2. Set doc to doc's associated inert template document.
  1931. return *m_associated_inert_template_document;
  1932. }
  1933. // 2. Return doc.
  1934. return *this;
  1935. }
  1936. DeprecatedString Document::dump_accessibility_tree_as_json()
  1937. {
  1938. StringBuilder builder;
  1939. auto accessibility_tree = AccessibilityTreeNode::create(this, nullptr).release_value_but_fixme_should_propagate_errors();
  1940. build_accessibility_tree(*&accessibility_tree);
  1941. auto json = MUST(JsonObjectSerializer<>::try_create(builder));
  1942. // Empty document
  1943. if (!accessibility_tree->value()) {
  1944. MUST(json.add("type"sv, "element"sv));
  1945. MUST(json.add("role"sv, "document"sv));
  1946. } else {
  1947. accessibility_tree->serialize_tree_as_json(json, *this);
  1948. }
  1949. MUST(json.finish());
  1950. return builder.to_deprecated_string();
  1951. }
  1952. // https://dom.spec.whatwg.org/#dom-document-createattribute
  1953. WebIDL::ExceptionOr<JS::NonnullGCPtr<Attr>> Document::create_attribute(DeprecatedString const& local_name)
  1954. {
  1955. // 1. If localName does not match the Name production in XML, then throw an "InvalidCharacterError" DOMException.
  1956. if (!is_valid_name(local_name))
  1957. return WebIDL::InvalidCharacterError::create(realm(), "Invalid character in attribute name.");
  1958. // 2. If this is an HTML document, then set localName to localName in ASCII lowercase.
  1959. // 3. Return a new attribute whose local name is localName and node document is this.
  1960. return Attr::create(*this, is_html_document() ? local_name.to_lowercase() : local_name);
  1961. }
  1962. // https://dom.spec.whatwg.org/#dom-document-createattributens
  1963. WebIDL::ExceptionOr<JS::NonnullGCPtr<Attr>> Document::create_attribute_ns(DeprecatedString const& namespace_, DeprecatedString const& qualified_name)
  1964. {
  1965. // 1. Let namespace, prefix, and localName be the result of passing namespace and qualifiedName to validate and extract.
  1966. auto extracted_qualified_name = TRY(validate_and_extract(realm(), namespace_, qualified_name));
  1967. // 2. Return a new attribute whose namespace is namespace, namespace prefix is prefix, local name is localName, and node document is this.
  1968. return Attr::create(*this, extracted_qualified_name);
  1969. }
  1970. }