Document.cpp 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021-2022, 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/StringBuilder.h>
  11. #include <AK/Utf8View.h>
  12. #include <LibCore/Timer.h>
  13. #include <LibJS/Interpreter.h>
  14. #include <LibJS/Parser.h>
  15. #include <LibJS/Runtime/FunctionObject.h>
  16. #include <LibWeb/Bindings/MainThreadVM.h>
  17. #include <LibWeb/Bindings/WindowObject.h>
  18. #include <LibWeb/CSS/MediaQueryListEvent.h>
  19. #include <LibWeb/CSS/StyleComputer.h>
  20. #include <LibWeb/Cookie/ParsedCookie.h>
  21. #include <LibWeb/DOM/Comment.h>
  22. #include <LibWeb/DOM/CustomEvent.h>
  23. #include <LibWeb/DOM/DOMException.h>
  24. #include <LibWeb/DOM/DOMImplementation.h>
  25. #include <LibWeb/DOM/Document.h>
  26. #include <LibWeb/DOM/DocumentFragment.h>
  27. #include <LibWeb/DOM/DocumentType.h>
  28. #include <LibWeb/DOM/Element.h>
  29. #include <LibWeb/DOM/ElementFactory.h>
  30. #include <LibWeb/DOM/Event.h>
  31. #include <LibWeb/DOM/ExceptionOr.h>
  32. #include <LibWeb/DOM/HTMLCollection.h>
  33. #include <LibWeb/DOM/NodeIterator.h>
  34. #include <LibWeb/DOM/Range.h>
  35. #include <LibWeb/DOM/ShadowRoot.h>
  36. #include <LibWeb/DOM/Text.h>
  37. #include <LibWeb/DOM/TreeWalker.h>
  38. #include <LibWeb/Dump.h>
  39. #include <LibWeb/HTML/AttributeNames.h>
  40. #include <LibWeb/HTML/BrowsingContext.h>
  41. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  42. #include <LibWeb/HTML/EventNames.h>
  43. #include <LibWeb/HTML/HTMLAnchorElement.h>
  44. #include <LibWeb/HTML/HTMLAreaElement.h>
  45. #include <LibWeb/HTML/HTMLBaseElement.h>
  46. #include <LibWeb/HTML/HTMLBodyElement.h>
  47. #include <LibWeb/HTML/HTMLEmbedElement.h>
  48. #include <LibWeb/HTML/HTMLFormElement.h>
  49. #include <LibWeb/HTML/HTMLFrameSetElement.h>
  50. #include <LibWeb/HTML/HTMLHeadElement.h>
  51. #include <LibWeb/HTML/HTMLHtmlElement.h>
  52. #include <LibWeb/HTML/HTMLIFrameElement.h>
  53. #include <LibWeb/HTML/HTMLImageElement.h>
  54. #include <LibWeb/HTML/HTMLLinkElement.h>
  55. #include <LibWeb/HTML/HTMLScriptElement.h>
  56. #include <LibWeb/HTML/HTMLTitleElement.h>
  57. #include <LibWeb/HTML/MessageEvent.h>
  58. #include <LibWeb/HTML/NavigationParams.h>
  59. #include <LibWeb/HTML/Origin.h>
  60. #include <LibWeb/HTML/Parser/HTMLParser.h>
  61. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  62. #include <LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.h>
  63. #include <LibWeb/HTML/Window.h>
  64. #include <LibWeb/Layout/BlockFormattingContext.h>
  65. #include <LibWeb/Layout/InitialContainingBlock.h>
  66. #include <LibWeb/Layout/TreeBuilder.h>
  67. #include <LibWeb/Namespace.h>
  68. #include <LibWeb/Page/Page.h>
  69. #include <LibWeb/SVG/TagNames.h>
  70. #include <LibWeb/UIEvents/EventNames.h>
  71. #include <LibWeb/UIEvents/FocusEvent.h>
  72. #include <LibWeb/UIEvents/KeyboardEvent.h>
  73. #include <LibWeb/UIEvents/MouseEvent.h>
  74. namespace Web::DOM {
  75. // https://html.spec.whatwg.org/multipage/origin.html#obtain-browsing-context-navigation
  76. static NonnullRefPtr<HTML::BrowsingContext> obtain_a_browsing_context_to_use_for_a_navigation_response(
  77. HTML::BrowsingContext& browsing_context,
  78. HTML::SandboxingFlagSet sandbox_flags,
  79. HTML::CrossOriginOpenerPolicy navigation_coop,
  80. HTML::CrossOriginOpenerPolicyEnforcementResult coop_enforcement_result)
  81. {
  82. // 1. If browsingContext is not a top-level browsing context, return browsingContext.
  83. if (!browsing_context.is_top_level())
  84. return browsing_context;
  85. // 2. If coopEnforcementResult's needs a browsing context group switch is false, then:
  86. if (!coop_enforcement_result.needs_a_browsing_context_group_switch) {
  87. // 1. If coopEnforcementResult's would need a browsing context group switch due to report-only is true,
  88. if (coop_enforcement_result.would_need_a_browsing_context_group_switch_due_to_report_only) {
  89. // FIXME: set browsing context's virtual browsing context group ID to a new unique identifier.
  90. }
  91. // 2. Return browsingContext.
  92. return browsing_context;
  93. }
  94. // 3. Let newBrowsingContext be the result of creating a new top-level browsing context.
  95. VERIFY(browsing_context.page());
  96. auto new_browsing_context = HTML::BrowsingContext::create_a_new_browsing_context(*browsing_context.page(), nullptr, nullptr);
  97. // FIXME: 4. If navigationCOOP's value is "same-origin-plus-COEP", then set newBrowsingContext's group's
  98. // cross-origin isolation mode to either "logical" or "concrete". The choice of which is implementation-defined.
  99. // 5. If sandboxFlags is not empty, then:
  100. if (!sandbox_flags.is_empty()) {
  101. // 1. Assert navigationCOOP's value is "unsafe-none".
  102. VERIFY(navigation_coop.value == HTML::CrossOriginOpenerPolicyValue::UnsafeNone);
  103. // 2. Assert: newBrowsingContext's popup sandboxing flag set is empty.
  104. // 3. Set newBrowsingContext's popup sandboxing flag set to a clone of sandboxFlags.
  105. }
  106. // FIXME: 6. Discard browsingContext.
  107. // 7. Return newBrowsingContext.
  108. return new_browsing_context;
  109. }
  110. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#initialise-the-document-object
  111. NonnullRefPtr<Document> Document::create_and_initialize(Type type, String content_type, HTML::NavigationParams navigation_params)
  112. {
  113. // 1. Let browsingContext be the result of the obtaining a browsing context to use for a navigation response
  114. // given navigationParams's browsing context, navigationParams's final sandboxing flag set,
  115. // navigationParams's cross-origin opener policy, and navigationParams's COOP enforcement result.
  116. auto browsing_context = obtain_a_browsing_context_to_use_for_a_navigation_response(
  117. navigation_params.browsing_context,
  118. navigation_params.final_sandboxing_flag_set,
  119. navigation_params.cross_origin_opener_policy,
  120. navigation_params.coop_enforcement_result);
  121. // FIXME: 2. Let permissionsPolicy be the result of creating a permissions policy from a response
  122. // given browsingContext, navigationParams's origin, and navigationParams's response.
  123. // 3. Let creationURL be navigationParams's response's URL.
  124. auto creation_url = navigation_params.response->url();
  125. // 4. If navigationParams's request is non-null, then set creationURL to navigationParams's request's current URL.
  126. if (navigation_params.request) {
  127. creation_url = navigation_params.request->current_url();
  128. }
  129. RefPtr<HTML::Window> window;
  130. // 5. If browsingContext is still on its initial about:blank Document,
  131. // and navigationParams's history handling is "replace",
  132. // and browsingContext's active document's origin is same origin-domain with navigationParams's origin,
  133. // then do nothing.
  134. if (browsing_context->still_on_its_initial_about_blank_document()
  135. && navigation_params.history_handling == HTML::HistoryHandlingBehavior::Replace
  136. && (browsing_context->active_document() && browsing_context->active_document()->origin().is_same_origin(navigation_params.origin))) {
  137. // Do nothing.
  138. }
  139. // 6. Otherwise:
  140. else {
  141. // FIXME: 1. Let oacHeader be the result of getting a structured field value given `Origin-Agent-Cluster` and "item" from response's header list.
  142. // FIXME: 2. Let requestsOAC be true if oacHeader is not null and oacHeader[0] is the boolean true; otherwise false.
  143. [[maybe_unused]] auto requests_oac = false;
  144. // FIXME: 3. If navigationParams's reserved environment is a non-secure context, then set requestsOAC to false.
  145. // FIXME: 4. Let agent be the result of obtaining a similar-origin window agent given navigationParams's origin, browsingContext's group, and requestsOAC.
  146. // 5. Let realm execution context be the result of creating a new JavaScript realm given agent and the following customizations:
  147. auto realm_execution_context = Bindings::create_a_new_javascript_realm(
  148. Bindings::main_thread_vm(),
  149. [&](JS::Realm& realm) -> JS::GlobalObject* {
  150. // - For the global object, create a new Window object.
  151. window = HTML::Window::create();
  152. auto* global_object = realm.heap().allocate_without_realm<Bindings::WindowObject>(realm, *window);
  153. VERIFY(window->wrapper() == global_object);
  154. return global_object;
  155. },
  156. [](JS::Realm&) -> JS::GlobalObject* {
  157. // FIXME: - For the global this binding, use browsingContext's WindowProxy object.
  158. return nullptr;
  159. });
  160. // 6. Let topLevelCreationURL be creationURL.
  161. auto top_level_creation_url = creation_url;
  162. // 7. Let topLevelOrigin be navigationParams's origin.
  163. auto top_level_origin = navigation_params.origin;
  164. // 8. If browsingContext is not a top-level browsing context, then:
  165. if (!browsing_context->is_top_level()) {
  166. // 1. Let parentEnvironment be browsingContext's container's relevant settings object.
  167. auto& parent_environment = browsing_context->container()->document().relevant_settings_object();
  168. // 2. Set topLevelCreationURL to parentEnvironment's top-level creation URL.
  169. top_level_creation_url = parent_environment.top_level_creation_url;
  170. // 3. Set topLevelOrigin to parentEnvironment's top-level origin.
  171. top_level_origin = parent_environment.top_level_origin;
  172. }
  173. // 9. Set up a window environment settings object with creationURL, realm execution context,
  174. // navigationParams's reserved environment, topLevelCreationURL, and topLevelOrigin.
  175. // FIXME: Why do we assume `creation_url` is non-empty here? Is this a spec bug?
  176. // FIXME: Why do we assume `top_level_creation_url` is non-empty here? Is this a spec bug?
  177. HTML::WindowEnvironmentSettingsObject::setup(
  178. creation_url.value(),
  179. move(realm_execution_context),
  180. navigation_params.reserved_environment,
  181. top_level_creation_url.value(),
  182. top_level_origin);
  183. }
  184. // 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.
  185. // 8. Let document be a new Document,
  186. // whose type is type,
  187. // content type is contentType,
  188. // origin is navigationParams's origin,
  189. // FIXME: policy container is navigationParams's policy container,
  190. // FIXME: permissions policy is permissionsPolicy,
  191. // FIXME: active sandboxing flag set is navigationParams's final sandboxing flag set,
  192. // FIXME: and cross-origin opener policy is navigationParams's cross-origin opener policy,
  193. // FIXME: load timing info is loadTimingInfo,
  194. // FIXME: and navigation id is navigationParams's id.
  195. auto document = Document::create();
  196. document->m_type = type;
  197. document->m_content_type = content_type;
  198. document->set_origin(navigation_params.origin);
  199. document->m_window = window;
  200. window->set_associated_document(*document);
  201. // 9. Set document's URL to creationURL.
  202. document->m_url = creation_url.value();
  203. // 10. Set document's current document readiness to "loading".
  204. document->m_readiness = HTML::DocumentReadyState::Loading;
  205. // FIXME: 11. Run CSP initialization for a Document given document.
  206. // 12. If navigationParams's request is non-null, then:
  207. if (navigation_params.request) {
  208. // FIXME: 1. Set document's referrer to the empty string.
  209. // FIXME: 2. Let referrer be navigationParams's request's referrer.
  210. // FIXME: 3. If referrer is a URL record, then set document's referrer to the serialization of referrer.
  211. }
  212. // FIXME: 13. Let historyHandling be navigationParams's history handling.
  213. // FIXME: 14: Let navigationTimingType be the result of switching on navigationParams's history handling...
  214. // FIXME: 15. Let redirectCount be 0 if navigationParams's has cross-origin redirects is true;
  215. // otherwise navigationParams's request's redirect count.
  216. // FIXME: 16. Create the navigation timing entry for document, with navigationParams's response's timing info,
  217. // redirectCount, navigationTimingType, and navigationParams's response's service worker timing info.
  218. // FIXME: 17. If navigationParams's response has a `Refresh` header, then...
  219. // FIXME: 18. If navigationParams's commit early hints is not null, then call navigationParams's commit early hints with document.
  220. // FIXME: 19. Process link headers given document, navigationParams's response, and "pre-media".
  221. // 20. Return document.
  222. return document;
  223. }
  224. NonnullRefPtr<Document> Document::create_with_global_object(Bindings::WindowObject&)
  225. {
  226. return Document::create();
  227. }
  228. NonnullRefPtr<Document> Document::create(AK::URL const& url)
  229. {
  230. return adopt_ref(*new Document(url));
  231. }
  232. Document::Document(const AK::URL& url)
  233. : ParentNode(*this, NodeType::DOCUMENT_NODE)
  234. , m_style_computer(make<CSS::StyleComputer>(*this))
  235. , m_url(url)
  236. , m_window(HTML::Window::create_with_document(*this))
  237. , m_implementation(DOMImplementation::create({}, *this))
  238. , m_history(HTML::History::create(*this))
  239. {
  240. m_style_sheets = JS::make_handle(CSS::StyleSheetList::create(*this));
  241. HTML::main_thread_event_loop().register_document({}, *this);
  242. m_style_update_timer = Core::Timer::create_single_shot(0, [this] {
  243. update_style();
  244. });
  245. m_layout_update_timer = Core::Timer::create_single_shot(0, [this] {
  246. force_layout();
  247. });
  248. }
  249. Document::~Document() = default;
  250. void Document::removed_last_ref()
  251. {
  252. VERIFY(!ref_count());
  253. VERIFY(!m_deletion_has_begun);
  254. if (m_referencing_node_count) {
  255. // The document has reached ref_count==0 but still has nodes keeping it alive.
  256. // At this point, sever all the node links we control.
  257. // If nodes remain elsewhere (e.g JS wrappers), they will keep the document alive.
  258. // NOTE: This makes sure we stay alive across for the duration of the cleanup below.
  259. increment_referencing_node_count();
  260. m_focused_element = nullptr;
  261. m_hovered_node = nullptr;
  262. m_pending_parsing_blocking_script = nullptr;
  263. m_inspected_node = nullptr;
  264. m_scripts_to_execute_when_parsing_has_finished.clear();
  265. m_scripts_to_execute_as_soon_as_possible.clear();
  266. m_associated_inert_template_document = nullptr;
  267. m_interpreter = nullptr;
  268. {
  269. // Gather up all the descendants of this document and prune them from the tree.
  270. // FIXME: This could definitely be more elegant.
  271. NonnullRefPtrVector<Node> descendants;
  272. for_each_in_inclusive_subtree([&](auto& node) {
  273. if (&node != this)
  274. descendants.append(node);
  275. return IterationDecision::Continue;
  276. });
  277. for (auto& node : descendants) {
  278. VERIFY(&node.document() == this);
  279. VERIFY(!node.is_document());
  280. if (node.parent()) {
  281. // We need to suppress mutation observers so that they don't try and queue a microtask for this Document which is in the process of dying,
  282. // which will cause an `!m_in_removed_last_ref` assertion failure when it tries to ref this Document.
  283. node.remove(true);
  284. }
  285. }
  286. }
  287. m_in_removed_last_ref = false;
  288. decrement_referencing_node_count();
  289. return;
  290. }
  291. m_in_removed_last_ref = false;
  292. m_deletion_has_begun = true;
  293. HTML::main_thread_event_loop().unregister_document({}, *this);
  294. delete this;
  295. }
  296. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-write
  297. ExceptionOr<void> Document::write(Vector<String> const& strings)
  298. {
  299. StringBuilder builder;
  300. builder.join(""sv, strings);
  301. return run_the_document_write_steps(builder.build());
  302. }
  303. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-writeln
  304. ExceptionOr<void> Document::writeln(Vector<String> const& strings)
  305. {
  306. StringBuilder builder;
  307. builder.join(""sv, strings);
  308. builder.append("\n"sv);
  309. return run_the_document_write_steps(builder.build());
  310. }
  311. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#document-write-steps
  312. ExceptionOr<void> Document::run_the_document_write_steps(String input)
  313. {
  314. // 1. If document is an XML document, then throw an "InvalidStateError" DOMException.
  315. if (m_type == Type::XML)
  316. return DOM::InvalidStateError::create("write() called on XML document.");
  317. // 2. If document's throw-on-dynamic-markup-insertion counter is greater than 0, then throw an "InvalidStateError" DOMException.
  318. if (m_throw_on_dynamic_markup_insertion_counter > 0)
  319. return DOM::InvalidStateError::create("throw-on-dynamic-markup-insertion-counter greater than zero.");
  320. // 3. If document's active parser was aborted is true, then return.
  321. if (m_active_parser_was_aborted)
  322. return {};
  323. // 4. If the insertion point is undefined, then:
  324. if (!(m_parser && m_parser->tokenizer().is_insertion_point_defined())) {
  325. // 1. If document's unload counter is greater than 0 or document's ignore-destructive-writes counter is greater than 0, then return.
  326. if (m_unload_counter > 0 || m_ignore_destructive_writes_counter > 0)
  327. return {};
  328. // 2. Run the document open steps with document.
  329. open();
  330. }
  331. // 5. Insert input into the input stream just before the insertion point.
  332. m_parser->tokenizer().insert_input_at_insertion_point(input);
  333. // 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).
  334. if (!pending_parsing_blocking_script())
  335. m_parser->run();
  336. return {};
  337. }
  338. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-open
  339. ExceptionOr<Document*> Document::open(String const&, String const&)
  340. {
  341. // 1. If document is an XML document, then throw an "InvalidStateError" DOMException exception.
  342. if (m_type == Type::XML)
  343. return DOM::InvalidStateError::create("open() called on XML document.");
  344. // 2. If document's throw-on-dynamic-markup-insertion counter is greater than 0, then throw an "InvalidStateError" DOMException.
  345. if (m_throw_on_dynamic_markup_insertion_counter > 0)
  346. return DOM::InvalidStateError::create("throw-on-dynamic-markup-insertion-counter greater than zero.");
  347. // FIXME: 3. Let entryDocument be the entry global object's associated Document.
  348. auto& entry_document = *this;
  349. // 4. If document's origin is not same origin to entryDocument's origin, then throw a "SecurityError" DOMException.
  350. if (origin() != entry_document.origin())
  351. return DOM::SecurityError::create("Document.origin() not the same as entryDocument's.");
  352. // 5. If document has an active parser whose script nesting level is greater than 0, then return document.
  353. if (m_parser && m_parser->script_nesting_level() > 0)
  354. return this;
  355. // 6. Similarly, if document's unload counter is greater than 0, then return document.
  356. if (m_unload_counter > 0)
  357. return this;
  358. // 7. If document's active parser was aborted is true, then return document.
  359. if (m_active_parser_was_aborted)
  360. return this;
  361. // 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.
  362. // FIXME: 9. For each shadow-including inclusive descendant node of document, erase all event listeners and handlers given node.
  363. // 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.
  364. // 11. Replace all with null within document, without firing any mutation events.
  365. replace_all(nullptr);
  366. // 12. If document is fully active, then:
  367. if (is_fully_active()) {
  368. // 1. Let newURL be a copy of entryDocument's URL.
  369. auto new_url = entry_document.url();
  370. // 2. If entryDocument is not document, then set newURL's fragment to null.
  371. if (&entry_document != this)
  372. new_url.set_fragment("");
  373. // FIXME: 3. Run the URL and history update steps with document and newURL.
  374. }
  375. // 13. Set document's is initial about:blank to false.
  376. set_is_initial_about_blank(false);
  377. // FIXME: 14. If document's iframe load in progress flag is set, then set document's mute iframe load flag.
  378. // 15. Set document to no-quirks mode.
  379. set_quirks_mode(QuirksMode::No);
  380. // 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.
  381. m_parser = HTML::HTMLParser::create_for_scripting(*this);
  382. // 17. Set the insertion point to point at just before the end of the input stream (which at this point will be empty).
  383. m_parser->tokenizer().update_insertion_point();
  384. // 18. Update the current document readiness of document to "loading".
  385. update_readiness(HTML::DocumentReadyState::Loading);
  386. // 19. Return document.
  387. return this;
  388. }
  389. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#closing-the-input-stream
  390. ExceptionOr<void> Document::close()
  391. {
  392. // 1. If document is an XML document, then throw an "InvalidStateError" DOMException exception.
  393. if (m_type == Type::XML)
  394. return DOM::InvalidStateError::create("close() called on XML document.");
  395. // 2. If document's throw-on-dynamic-markup-insertion counter is greater than 0, then throw an "InvalidStateError" DOMException.
  396. if (m_throw_on_dynamic_markup_insertion_counter > 0)
  397. return DOM::InvalidStateError::create("throw-on-dynamic-markup-insertion-counter greater than zero.");
  398. // 3. If there is no script-created parser associated with the document, then return.
  399. if (!m_parser)
  400. return {};
  401. // FIXME: 4. Insert an explicit "EOF" character at the end of the parser's input stream.
  402. m_parser->tokenizer().insert_eof();
  403. // 5. If there is a pending parsing-blocking script, then return.
  404. if (pending_parsing_blocking_script())
  405. return {};
  406. // 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.
  407. m_parser->run();
  408. return {};
  409. }
  410. HTML::Origin Document::origin() const
  411. {
  412. return m_origin;
  413. }
  414. void Document::set_origin(HTML::Origin const& origin)
  415. {
  416. m_origin = origin;
  417. }
  418. void Document::schedule_style_update()
  419. {
  420. if (m_style_update_timer->is_active())
  421. return;
  422. m_style_update_timer->start();
  423. }
  424. void Document::schedule_layout_update()
  425. {
  426. if (m_layout_update_timer->is_active())
  427. return;
  428. m_layout_update_timer->start();
  429. }
  430. bool Document::is_child_allowed(Node const& node) const
  431. {
  432. switch (node.type()) {
  433. case NodeType::DOCUMENT_NODE:
  434. case NodeType::TEXT_NODE:
  435. return false;
  436. case NodeType::COMMENT_NODE:
  437. return true;
  438. case NodeType::DOCUMENT_TYPE_NODE:
  439. return !first_child_of_type<DocumentType>();
  440. case NodeType::ELEMENT_NODE:
  441. return !first_child_of_type<Element>();
  442. default:
  443. return false;
  444. }
  445. }
  446. Element* Document::document_element()
  447. {
  448. return first_child_of_type<Element>();
  449. }
  450. Element const* Document::document_element() const
  451. {
  452. return first_child_of_type<Element>();
  453. }
  454. HTML::HTMLHtmlElement* Document::html_element()
  455. {
  456. auto* html = document_element();
  457. if (is<HTML::HTMLHtmlElement>(html))
  458. return verify_cast<HTML::HTMLHtmlElement>(html);
  459. return nullptr;
  460. }
  461. HTML::HTMLHeadElement* Document::head()
  462. {
  463. auto* html = html_element();
  464. if (!html)
  465. return nullptr;
  466. return html->first_child_of_type<HTML::HTMLHeadElement>();
  467. }
  468. HTML::HTMLElement* Document::body()
  469. {
  470. auto* html = html_element();
  471. if (!html)
  472. return nullptr;
  473. auto* first_body = html->first_child_of_type<HTML::HTMLBodyElement>();
  474. if (first_body)
  475. return first_body;
  476. auto* first_frameset = html->first_child_of_type<HTML::HTMLFrameSetElement>();
  477. if (first_frameset)
  478. return first_frameset;
  479. return nullptr;
  480. }
  481. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-body
  482. ExceptionOr<void> Document::set_body(HTML::HTMLElement* new_body)
  483. {
  484. if (!is<HTML::HTMLBodyElement>(new_body) && !is<HTML::HTMLFrameSetElement>(new_body))
  485. return DOM::HierarchyRequestError::create("Invalid document body element, must be 'body' or 'frameset'");
  486. auto* existing_body = body();
  487. if (existing_body) {
  488. (void)TRY(existing_body->parent()->replace_child(*new_body, *existing_body));
  489. return {};
  490. }
  491. auto* document_element = this->document_element();
  492. if (!document_element)
  493. return DOM::HierarchyRequestError::create("Missing document element");
  494. (void)TRY(document_element->append_child(*new_body));
  495. return {};
  496. }
  497. String Document::title() const
  498. {
  499. auto* head_element = head();
  500. if (!head_element)
  501. return {};
  502. auto* title_element = head_element->first_child_of_type<HTML::HTMLTitleElement>();
  503. if (!title_element)
  504. return {};
  505. auto raw_title = title_element->text_content();
  506. StringBuilder builder;
  507. bool last_was_space = false;
  508. for (auto code_point : Utf8View(raw_title)) {
  509. if (is_ascii_space(code_point)) {
  510. last_was_space = true;
  511. } else {
  512. if (last_was_space && !builder.is_empty())
  513. builder.append(' ');
  514. builder.append_code_point(code_point);
  515. last_was_space = false;
  516. }
  517. }
  518. return builder.to_string();
  519. }
  520. void Document::set_title(String const& title)
  521. {
  522. auto* head_element = const_cast<HTML::HTMLHeadElement*>(head());
  523. if (!head_element)
  524. return;
  525. RefPtr<HTML::HTMLTitleElement> title_element = head_element->first_child_of_type<HTML::HTMLTitleElement>();
  526. if (!title_element) {
  527. title_element = static_ptr_cast<HTML::HTMLTitleElement>(create_element(HTML::TagNames::title).release_value());
  528. head_element->append_child(*title_element);
  529. }
  530. title_element->remove_all_children(true);
  531. title_element->append_child(adopt_ref(*new Text(*this, title)));
  532. if (auto* page = this->page()) {
  533. if (browsing_context() == &page->top_level_browsing_context())
  534. page->client().page_did_change_title(title);
  535. }
  536. }
  537. void Document::attach_to_browsing_context(Badge<HTML::BrowsingContext>, HTML::BrowsingContext& browsing_context)
  538. {
  539. m_browsing_context = browsing_context;
  540. }
  541. void Document::detach_from_browsing_context(Badge<HTML::BrowsingContext>, HTML::BrowsingContext& browsing_context)
  542. {
  543. VERIFY(&browsing_context == m_browsing_context);
  544. tear_down_layout_tree();
  545. m_browsing_context = nullptr;
  546. }
  547. void Document::tear_down_layout_tree()
  548. {
  549. if (!m_layout_root)
  550. return;
  551. // Gather up all the layout nodes in a vector and detach them from parents
  552. // while the vector keeps them alive.
  553. NonnullRefPtrVector<Layout::Node> layout_nodes;
  554. m_layout_root->for_each_in_inclusive_subtree([&](auto& layout_node) {
  555. layout_nodes.append(layout_node);
  556. return IterationDecision::Continue;
  557. });
  558. for (auto& layout_node : layout_nodes) {
  559. if (layout_node.parent())
  560. layout_node.parent()->remove_child(layout_node);
  561. }
  562. m_layout_root = nullptr;
  563. }
  564. Color Document::background_color(Gfx::Palette const& palette) const
  565. {
  566. // CSS2 says we should use the HTML element's background color unless it's transparent...
  567. if (auto* html_element = this->html_element(); html_element && html_element->layout_node()) {
  568. auto color = html_element->layout_node()->computed_values().background_color();
  569. if (color.alpha())
  570. return color;
  571. }
  572. // ...in which case we use the BODY element's background color.
  573. if (auto* body_element = body(); body_element && body_element->layout_node()) {
  574. auto color = body_element->layout_node()->computed_values().background_color();
  575. if (color.alpha())
  576. return color;
  577. }
  578. // If both HTML and BODY are transparent, we fall back to the system's "base" palette color.
  579. return palette.base();
  580. }
  581. Vector<CSS::BackgroundLayerData> const* Document::background_layers() const
  582. {
  583. auto* body_element = body();
  584. if (!body_element)
  585. return {};
  586. auto* body_layout_node = body_element->layout_node();
  587. if (!body_layout_node)
  588. return {};
  589. return &body_layout_node->background_layers();
  590. }
  591. RefPtr<HTML::HTMLBaseElement> Document::first_base_element_with_href_in_tree_order() const
  592. {
  593. RefPtr<HTML::HTMLBaseElement> base_element;
  594. for_each_in_subtree_of_type<HTML::HTMLBaseElement>([&base_element](HTML::HTMLBaseElement const& base_element_in_tree) {
  595. if (base_element_in_tree.has_attribute(HTML::AttributeNames::href)) {
  596. base_element = base_element_in_tree;
  597. return IterationDecision::Break;
  598. }
  599. return IterationDecision::Continue;
  600. });
  601. return base_element;
  602. }
  603. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#fallback-base-url
  604. AK::URL Document::fallback_base_url() const
  605. {
  606. // FIXME: 1. If document is an iframe srcdoc document, then return the document base URL of document's browsing context's container document.
  607. // FIXME: 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.
  608. // 3. Return document's URL.
  609. return m_url;
  610. }
  611. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#document-base-url
  612. AK::URL Document::base_url() const
  613. {
  614. // 1. If there is no base element that has an href attribute in the Document, then return the Document's fallback base URL.
  615. auto base_element = first_base_element_with_href_in_tree_order();
  616. if (!base_element)
  617. return fallback_base_url();
  618. // 2. Otherwise, return the frozen base URL of the first base element in the Document that has an href attribute, in tree order.
  619. return base_element->frozen_base_url();
  620. }
  621. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#parse-a-url
  622. AK::URL Document::parse_url(String const& url) const
  623. {
  624. // FIXME: Pass in document's character encoding.
  625. return base_url().complete_url(url);
  626. }
  627. void Document::set_needs_layout()
  628. {
  629. if (m_needs_layout)
  630. return;
  631. m_needs_layout = true;
  632. schedule_layout_update();
  633. }
  634. void Document::force_layout()
  635. {
  636. tear_down_layout_tree();
  637. update_layout();
  638. }
  639. void Document::invalidate_layout()
  640. {
  641. tear_down_layout_tree();
  642. }
  643. void Document::update_layout()
  644. {
  645. // NOTE: If our parent document needs a relayout, we must do that *first*.
  646. // This is necessary as the parent layout may cause our viewport to change.
  647. if (browsing_context() && browsing_context()->container())
  648. browsing_context()->container()->document().update_layout();
  649. update_style();
  650. if (!m_needs_layout && m_layout_root)
  651. return;
  652. if (!browsing_context())
  653. return;
  654. auto viewport_rect = browsing_context()->viewport_rect();
  655. if (!m_layout_root) {
  656. m_next_layout_node_serial_id = 0;
  657. Layout::TreeBuilder tree_builder;
  658. m_layout_root = static_ptr_cast<Layout::InitialContainingBlock>(tree_builder.build(*this));
  659. }
  660. Layout::LayoutState layout_state;
  661. layout_state.used_values_per_layout_node.resize(layout_node_count());
  662. {
  663. Layout::BlockFormattingContext root_formatting_context(layout_state, *m_layout_root, nullptr);
  664. auto& icb = static_cast<Layout::InitialContainingBlock&>(*m_layout_root);
  665. auto& icb_state = layout_state.get_mutable(icb);
  666. icb_state.set_has_definite_width(true);
  667. icb_state.set_has_definite_height(true);
  668. icb_state.set_content_width(viewport_rect.width());
  669. icb_state.set_content_height(viewport_rect.height());
  670. root_formatting_context.run(*m_layout_root, Layout::LayoutMode::Normal);
  671. }
  672. layout_state.commit();
  673. browsing_context()->set_needs_display();
  674. if (browsing_context()->is_top_level()) {
  675. if (auto* page = this->page())
  676. page->client().page_did_layout();
  677. }
  678. m_needs_layout = false;
  679. m_layout_update_timer->stop();
  680. }
  681. [[nodiscard]] static bool update_style_recursively(DOM::Node& node)
  682. {
  683. bool const needs_full_style_update = node.document().needs_full_style_update();
  684. bool needs_relayout = false;
  685. if (is<Element>(node)) {
  686. needs_relayout |= static_cast<Element&>(node).recompute_style() == Element::NeedsRelayout::Yes;
  687. }
  688. node.set_needs_style_update(false);
  689. if (needs_full_style_update || node.child_needs_style_update()) {
  690. if (node.is_element()) {
  691. if (auto* shadow_root = static_cast<DOM::Element&>(node).shadow_root()) {
  692. if (needs_full_style_update || shadow_root->needs_style_update() || shadow_root->child_needs_style_update())
  693. needs_relayout |= update_style_recursively(*shadow_root);
  694. }
  695. }
  696. node.for_each_child([&](auto& child) {
  697. if (needs_full_style_update || child.needs_style_update() || child.child_needs_style_update())
  698. needs_relayout |= update_style_recursively(child);
  699. return IterationDecision::Continue;
  700. });
  701. }
  702. node.set_child_needs_style_update(false);
  703. return needs_relayout;
  704. }
  705. void Document::update_style()
  706. {
  707. if (!browsing_context())
  708. return;
  709. if (!needs_full_style_update() && !needs_style_update() && !child_needs_style_update())
  710. return;
  711. evaluate_media_rules();
  712. if (update_style_recursively(*this))
  713. invalidate_layout();
  714. m_needs_full_style_update = false;
  715. m_style_update_timer->stop();
  716. }
  717. void Document::set_link_color(Color color)
  718. {
  719. m_link_color = color;
  720. }
  721. void Document::set_active_link_color(Color color)
  722. {
  723. m_active_link_color = color;
  724. }
  725. void Document::set_visited_link_color(Color color)
  726. {
  727. m_visited_link_color = color;
  728. }
  729. Layout::InitialContainingBlock const* Document::layout_node() const
  730. {
  731. return static_cast<Layout::InitialContainingBlock const*>(Node::layout_node());
  732. }
  733. Layout::InitialContainingBlock* Document::layout_node()
  734. {
  735. return static_cast<Layout::InitialContainingBlock*>(Node::layout_node());
  736. }
  737. void Document::set_inspected_node(Node* node)
  738. {
  739. if (m_inspected_node == node)
  740. return;
  741. if (m_inspected_node && m_inspected_node->layout_node())
  742. m_inspected_node->layout_node()->set_needs_display();
  743. m_inspected_node = node;
  744. if (m_inspected_node && m_inspected_node->layout_node())
  745. m_inspected_node->layout_node()->set_needs_display();
  746. }
  747. static Node* find_common_ancestor(Node* a, Node* b)
  748. {
  749. if (!a || !b)
  750. return nullptr;
  751. if (a == b)
  752. return a;
  753. HashTable<Node*> ancestors;
  754. for (auto* node = a; node; node = node->parent_or_shadow_host())
  755. ancestors.set(node);
  756. for (auto* node = b; node; node = node->parent_or_shadow_host()) {
  757. if (ancestors.contains(node))
  758. return node;
  759. }
  760. return nullptr;
  761. }
  762. void Document::set_hovered_node(Node* node)
  763. {
  764. if (m_hovered_node == node)
  765. return;
  766. RefPtr<Node> old_hovered_node = move(m_hovered_node);
  767. m_hovered_node = node;
  768. if (auto* common_ancestor = find_common_ancestor(old_hovered_node, m_hovered_node))
  769. common_ancestor->invalidate_style();
  770. else
  771. invalidate_style();
  772. }
  773. NonnullRefPtr<HTMLCollection> Document::get_elements_by_name(String const& name)
  774. {
  775. return HTMLCollection::create(*this, [name](Element const& element) {
  776. return element.name() == name;
  777. });
  778. }
  779. NonnullRefPtr<HTMLCollection> Document::get_elements_by_class_name(FlyString const& class_name)
  780. {
  781. return HTMLCollection::create(*this, [class_name, quirks_mode = document().in_quirks_mode()](Element const& element) {
  782. return element.has_class(class_name, quirks_mode ? CaseSensitivity::CaseInsensitive : CaseSensitivity::CaseSensitive);
  783. });
  784. }
  785. // https://html.spec.whatwg.org/multipage/obsolete.html#dom-document-applets
  786. NonnullRefPtr<HTMLCollection> Document::applets()
  787. {
  788. // FIXME: This should return the same HTMLCollection object every time,
  789. // but that would cause a reference cycle since HTMLCollection refs the root.
  790. return HTMLCollection::create(*this, [](auto&) { return false; });
  791. }
  792. // https://html.spec.whatwg.org/multipage/obsolete.html#dom-document-anchors
  793. NonnullRefPtr<HTMLCollection> Document::anchors()
  794. {
  795. // FIXME: This should return the same HTMLCollection object every time,
  796. // but that would cause a reference cycle since HTMLCollection refs the root.
  797. return HTMLCollection::create(*this, [](Element const& element) {
  798. return is<HTML::HTMLAnchorElement>(element) && element.has_attribute(HTML::AttributeNames::name);
  799. });
  800. }
  801. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-images
  802. NonnullRefPtr<HTMLCollection> Document::images()
  803. {
  804. // FIXME: This should return the same HTMLCollection object every time,
  805. // but that would cause a reference cycle since HTMLCollection refs the root.
  806. return HTMLCollection::create(*this, [](Element const& element) {
  807. return is<HTML::HTMLImageElement>(element);
  808. });
  809. }
  810. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-embeds
  811. NonnullRefPtr<HTMLCollection> Document::embeds()
  812. {
  813. // FIXME: This should return the same HTMLCollection object every time,
  814. // but that would cause a reference cycle since HTMLCollection refs the root.
  815. return HTMLCollection::create(*this, [](Element const& element) {
  816. return is<HTML::HTMLEmbedElement>(element);
  817. });
  818. }
  819. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-plugins
  820. NonnullRefPtr<HTMLCollection> Document::plugins()
  821. {
  822. return embeds();
  823. }
  824. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-links
  825. NonnullRefPtr<HTMLCollection> Document::links()
  826. {
  827. // FIXME: This should return the same HTMLCollection object every time,
  828. // but that would cause a reference cycle since HTMLCollection refs the root.
  829. return HTMLCollection::create(*this, [](Element const& element) {
  830. return (is<HTML::HTMLAnchorElement>(element) || is<HTML::HTMLAreaElement>(element)) && element.has_attribute(HTML::AttributeNames::href);
  831. });
  832. }
  833. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-forms
  834. NonnullRefPtr<HTMLCollection> Document::forms()
  835. {
  836. // FIXME: This should return the same HTMLCollection object every time,
  837. // but that would cause a reference cycle since HTMLCollection refs the root.
  838. return HTMLCollection::create(*this, [](Element const& element) {
  839. return is<HTML::HTMLFormElement>(element);
  840. });
  841. }
  842. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-scripts
  843. NonnullRefPtr<HTMLCollection> Document::scripts()
  844. {
  845. // FIXME: This should return the same HTMLCollection object every time,
  846. // but that would cause a reference cycle since HTMLCollection refs the root.
  847. return HTMLCollection::create(*this, [](Element const& element) {
  848. return is<HTML::HTMLScriptElement>(element);
  849. });
  850. }
  851. Color Document::link_color() const
  852. {
  853. if (m_link_color.has_value())
  854. return m_link_color.value();
  855. if (!page())
  856. return Color::Blue;
  857. return page()->palette().link();
  858. }
  859. Color Document::active_link_color() const
  860. {
  861. if (m_active_link_color.has_value())
  862. return m_active_link_color.value();
  863. if (!page())
  864. return Color::Red;
  865. return page()->palette().active_link();
  866. }
  867. Color Document::visited_link_color() const
  868. {
  869. if (m_visited_link_color.has_value())
  870. return m_visited_link_color.value();
  871. if (!page())
  872. return Color::Magenta;
  873. return page()->palette().visited_link();
  874. }
  875. // https://html.spec.whatwg.org/multipage/webappapis.html#relevant-settings-object
  876. HTML::EnvironmentSettingsObject& Document::relevant_settings_object()
  877. {
  878. // Then, the relevant settings object for a platform object o is the environment settings object of the relevant Realm for o.
  879. return verify_cast<HTML::EnvironmentSettingsObject>(*realm().host_defined());
  880. }
  881. JS::Realm& Document::realm()
  882. {
  883. VERIFY(m_window);
  884. VERIFY(m_window->wrapper());
  885. return m_window->wrapper()->shape().realm();
  886. }
  887. JS::Interpreter& Document::interpreter()
  888. {
  889. if (!m_interpreter) {
  890. m_interpreter = JS::Interpreter::create_with_existing_realm(realm());
  891. }
  892. return *m_interpreter;
  893. }
  894. JS::Value Document::run_javascript(StringView source, StringView filename)
  895. {
  896. // 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
  897. auto& interpreter = document().interpreter();
  898. auto script_or_error = JS::Script::parse(source, interpreter.realm(), filename);
  899. if (script_or_error.is_error()) {
  900. // FIXME: Add error logging back.
  901. return JS::js_undefined();
  902. }
  903. auto result = interpreter.run(script_or_error.value());
  904. if (result.is_error()) {
  905. // FIXME: I'm sure the spec could tell us something about error propagation here!
  906. HTML::report_exception(result);
  907. return {};
  908. }
  909. return result.value();
  910. }
  911. // https://dom.spec.whatwg.org/#dom-document-createelement
  912. // FIXME: This only implements step 6 of the algorithm and does not take in options.
  913. DOM::ExceptionOr<NonnullRefPtr<Element>> Document::create_element(String const& tag_name)
  914. {
  915. if (!is_valid_name(tag_name))
  916. return DOM::InvalidCharacterError::create("Invalid character in tag name.");
  917. // FIXME: Let namespace be the HTML namespace, if this is an HTML document or this’s content type is "application/xhtml+xml", and null otherwise.
  918. return DOM::create_element(*this, tag_name, Namespace::HTML);
  919. }
  920. // https://dom.spec.whatwg.org/#dom-document-createelementns
  921. // https://dom.spec.whatwg.org/#internal-createelementns-steps
  922. // FIXME: This only implements step 4 of the algorithm and does not take in options.
  923. DOM::ExceptionOr<NonnullRefPtr<Element>> Document::create_element_ns(String const& namespace_, String const& qualified_name)
  924. {
  925. // 1. Let namespace, prefix, and localName be the result of passing namespace and qualifiedName to validate and extract.
  926. auto extracted_qualified_name = TRY(validate_and_extract(namespace_, qualified_name));
  927. // FIXME: 2. Let is be null.
  928. // FIXME: 3. If options is a dictionary and options["is"] exists, then set is to it.
  929. // 4. Return the result of creating an element given document, localName, namespace, prefix, is, and with the synchronous custom elements flag set.
  930. return DOM::create_element(*this, extracted_qualified_name.local_name(), extracted_qualified_name.namespace_(), extracted_qualified_name.prefix());
  931. }
  932. NonnullRefPtr<DocumentFragment> Document::create_document_fragment()
  933. {
  934. return adopt_ref(*new DocumentFragment(*this));
  935. }
  936. NonnullRefPtr<Text> Document::create_text_node(String const& data)
  937. {
  938. return adopt_ref(*new Text(*this, data));
  939. }
  940. NonnullRefPtr<Comment> Document::create_comment(String const& data)
  941. {
  942. return adopt_ref(*new Comment(*this, data));
  943. }
  944. NonnullRefPtr<Range> Document::create_range()
  945. {
  946. return Range::create(*this);
  947. }
  948. // https://dom.spec.whatwg.org/#dom-document-createevent
  949. DOM::ExceptionOr<NonnullRefPtr<Event>> Document::create_event(String const& interface)
  950. {
  951. // NOTE: This is named event here, since we do step 5 and 6 as soon as possible for each case.
  952. // 1. Let constructor be null.
  953. RefPtr<Event> event;
  954. // 2. If interface is an ASCII case-insensitive match for any of the strings in the first column in the following table,
  955. // then set constructor to the interface in the second column on the same row as the matching string:
  956. auto interface_lowercase = interface.to_lowercase();
  957. if (interface_lowercase == "beforeunloadevent") {
  958. event = Event::create(""); // FIXME: Create BeforeUnloadEvent
  959. } else if (interface_lowercase == "compositionevent") {
  960. event = Event::create(""); // FIXME: Create CompositionEvent
  961. } else if (interface_lowercase == "customevent") {
  962. event = CustomEvent::create("");
  963. } else if (interface_lowercase == "devicemotionevent") {
  964. event = Event::create(""); // FIXME: Create DeviceMotionEvent
  965. } else if (interface_lowercase == "deviceorientationevent") {
  966. event = Event::create(""); // FIXME: Create DeviceOrientationEvent
  967. } else if (interface_lowercase == "dragevent") {
  968. event = Event::create(""); // FIXME: Create DragEvent
  969. } else if (interface_lowercase.is_one_of("event", "events")) {
  970. event = Event::create("");
  971. } else if (interface_lowercase == "focusevent") {
  972. event = UIEvents::FocusEvent::create("");
  973. } else if (interface_lowercase == "hashchangeevent") {
  974. event = Event::create(""); // FIXME: Create HashChangeEvent
  975. } else if (interface_lowercase == "htmlevents") {
  976. event = Event::create("");
  977. } else if (interface_lowercase == "keyboardevent") {
  978. event = UIEvents::KeyboardEvent::create("");
  979. } else if (interface_lowercase == "messageevent") {
  980. event = HTML::MessageEvent::create("");
  981. } else if (interface_lowercase.is_one_of("mouseevent", "mouseevents")) {
  982. event = UIEvents::MouseEvent::create("");
  983. } else if (interface_lowercase == "storageevent") {
  984. event = Event::create(""); // FIXME: Create StorageEvent
  985. } else if (interface_lowercase == "svgevents") {
  986. event = Event::create("");
  987. } else if (interface_lowercase == "textevent") {
  988. event = Event::create(""); // FIXME: Create CompositionEvent
  989. } else if (interface_lowercase == "touchevent") {
  990. event = Event::create(""); // FIXME: Create TouchEvent
  991. } else if (interface_lowercase.is_one_of("uievent", "uievents")) {
  992. event = UIEvents::UIEvent::create("");
  993. }
  994. // 3. If constructor is null, then throw a "NotSupportedError" DOMException.
  995. if (!event) {
  996. return DOM::NotSupportedError::create("No constructor for interface found");
  997. }
  998. // FIXME: 4. If the interface indicated by constructor is not exposed on the relevant global object of this, then throw a "NotSupportedError" DOMException.
  999. // NOTE: These are done in the if-chain above
  1000. // 5. Let event be the result of creating an event given constructor.
  1001. // 6. Initialize event’s type attribute to the empty string.
  1002. // NOTE: This is handled by each constructor.
  1003. // FIXME: 7. Initialize event’s timeStamp attribute to the result of calling current high resolution time with this’s relevant global object.
  1004. // 8. Initialize event’s isTrusted attribute to false.
  1005. event->set_is_trusted(false);
  1006. // 9. Unset event’s initialized flag.
  1007. event->set_initialized(false);
  1008. // 10. Return event.
  1009. return event.release_nonnull();
  1010. }
  1011. void Document::set_pending_parsing_blocking_script(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement* script)
  1012. {
  1013. m_pending_parsing_blocking_script = script;
  1014. }
  1015. NonnullRefPtr<HTML::HTMLScriptElement> Document::take_pending_parsing_blocking_script(Badge<HTML::HTMLParser>)
  1016. {
  1017. return m_pending_parsing_blocking_script.release_nonnull();
  1018. }
  1019. void Document::add_script_to_execute_when_parsing_has_finished(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement& script)
  1020. {
  1021. m_scripts_to_execute_when_parsing_has_finished.append(script);
  1022. }
  1023. NonnullRefPtrVector<HTML::HTMLScriptElement> Document::take_scripts_to_execute_when_parsing_has_finished(Badge<HTML::HTMLParser>)
  1024. {
  1025. return move(m_scripts_to_execute_when_parsing_has_finished);
  1026. }
  1027. void Document::add_script_to_execute_as_soon_as_possible(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement& script)
  1028. {
  1029. m_scripts_to_execute_as_soon_as_possible.append(script);
  1030. }
  1031. NonnullRefPtrVector<HTML::HTMLScriptElement> Document::take_scripts_to_execute_as_soon_as_possible(Badge<HTML::HTMLParser>)
  1032. {
  1033. return move(m_scripts_to_execute_as_soon_as_possible);
  1034. }
  1035. // https://dom.spec.whatwg.org/#dom-document-importnode
  1036. ExceptionOr<NonnullRefPtr<Node>> Document::import_node(NonnullRefPtr<Node> node, bool deep)
  1037. {
  1038. // 1. If node is a document or shadow root, then throw a "NotSupportedError" DOMException.
  1039. if (is<Document>(*node) || is<ShadowRoot>(*node))
  1040. return DOM::NotSupportedError::create("Cannot import a document or shadow root.");
  1041. // 2. Return a clone of node, with this and the clone children flag set if deep is true.
  1042. return node->clone_node(this, deep);
  1043. }
  1044. // https://dom.spec.whatwg.org/#concept-node-adopt
  1045. void Document::adopt_node(Node& node)
  1046. {
  1047. auto& old_document = node.document();
  1048. if (node.parent())
  1049. node.remove();
  1050. if (&old_document != this) {
  1051. node.for_each_shadow_including_descendant([&](auto& inclusive_descendant) {
  1052. inclusive_descendant.set_document({}, *this);
  1053. // FIXME: If inclusiveDescendant is an element, then set the node document of each attribute in inclusiveDescendant’s attribute list to document.
  1054. return IterationDecision::Continue;
  1055. });
  1056. // FIXME: For each inclusiveDescendant in node’s shadow-including inclusive descendants that is custom,
  1057. // enqueue a custom element callback reaction with inclusiveDescendant, callback name "adoptedCallback",
  1058. // and an argument list containing oldDocument and document.
  1059. node.for_each_shadow_including_descendant([&](auto& inclusive_descendant) {
  1060. inclusive_descendant.adopted_from(old_document);
  1061. return IterationDecision::Continue;
  1062. });
  1063. // Transfer NodeIterators rooted at `node` from old_document to this document.
  1064. Vector<NodeIterator&> node_iterators_to_transfer;
  1065. for (auto* node_iterator : old_document.m_node_iterators) {
  1066. if (node_iterator->root() == &node)
  1067. node_iterators_to_transfer.append(*node_iterator);
  1068. }
  1069. for (auto& node_iterator : node_iterators_to_transfer) {
  1070. old_document.m_node_iterators.remove(&node_iterator);
  1071. m_node_iterators.set(&node_iterator);
  1072. }
  1073. }
  1074. }
  1075. // https://dom.spec.whatwg.org/#dom-document-adoptnode
  1076. ExceptionOr<NonnullRefPtr<Node>> Document::adopt_node_binding(NonnullRefPtr<Node> node)
  1077. {
  1078. if (is<Document>(*node))
  1079. return DOM::NotSupportedError::create("Cannot adopt a document into a document");
  1080. if (is<ShadowRoot>(*node))
  1081. return DOM::HierarchyRequestError::create("Cannot adopt a shadow root into a document");
  1082. if (is<DocumentFragment>(*node) && verify_cast<DocumentFragment>(*node).host())
  1083. return node;
  1084. adopt_node(*node);
  1085. return node;
  1086. }
  1087. DocumentType const* Document::doctype() const
  1088. {
  1089. return first_child_of_type<DocumentType>();
  1090. }
  1091. String const& Document::compat_mode() const
  1092. {
  1093. static String back_compat = "BackCompat";
  1094. static String css1_compat = "CSS1Compat";
  1095. if (m_quirks_mode == QuirksMode::Yes)
  1096. return back_compat;
  1097. return css1_compat;
  1098. }
  1099. bool Document::is_editable() const
  1100. {
  1101. return m_editable;
  1102. }
  1103. void Document::set_focused_element(Element* element)
  1104. {
  1105. if (m_focused_element == element)
  1106. return;
  1107. if (m_focused_element) {
  1108. m_focused_element->did_lose_focus();
  1109. m_focused_element->set_needs_style_update(true);
  1110. }
  1111. m_focused_element = element;
  1112. if (m_focused_element) {
  1113. m_focused_element->did_receive_focus();
  1114. m_focused_element->set_needs_style_update(true);
  1115. }
  1116. if (m_layout_root)
  1117. m_layout_root->set_needs_display();
  1118. }
  1119. void Document::set_active_element(Element* element)
  1120. {
  1121. if (m_active_element == element)
  1122. return;
  1123. m_active_element = element;
  1124. if (m_layout_root)
  1125. m_layout_root->set_needs_display();
  1126. }
  1127. String Document::ready_state() const
  1128. {
  1129. switch (m_readiness) {
  1130. case HTML::DocumentReadyState::Loading:
  1131. return "loading"sv;
  1132. case HTML::DocumentReadyState::Interactive:
  1133. return "interactive"sv;
  1134. case HTML::DocumentReadyState::Complete:
  1135. return "complete"sv;
  1136. }
  1137. VERIFY_NOT_REACHED();
  1138. }
  1139. // https://html.spec.whatwg.org/#update-the-current-document-readiness
  1140. void Document::update_readiness(HTML::DocumentReadyState readiness_value)
  1141. {
  1142. // 1. If document's current document readiness equals readinessValue, then return.
  1143. if (m_readiness == readiness_value)
  1144. return;
  1145. // The spec doesn't actually mention updating the current readiness value.
  1146. // FIXME: https://github.com/whatwg/html/issues/7120
  1147. m_readiness = readiness_value;
  1148. // FIXME: 2. If document is associated with an HTML parser, then:
  1149. // FIXME: 1. If document is associated with an HTML parser, then:
  1150. // FIXME: 2. If readinessValue is "complete", and document's load timing info's DOM complete time is 0, then set document's load timing info's DOM complete time to now.
  1151. // FIXME: 3. Otherwise, if readinessValue is "interactive", and document's load timing info's DOM interactive time is 0, then set document's load timing info's DOM interactive time to now.
  1152. // 3. Fire an event named readystatechange at document.
  1153. dispatch_event(Event::create(HTML::EventNames::readystatechange));
  1154. }
  1155. Page* Document::page()
  1156. {
  1157. return m_browsing_context ? m_browsing_context->page() : nullptr;
  1158. }
  1159. Page const* Document::page() const
  1160. {
  1161. return m_browsing_context ? m_browsing_context->page() : nullptr;
  1162. }
  1163. EventTarget* Document::get_parent(Event const& event)
  1164. {
  1165. if (event.type() == HTML::EventNames::load)
  1166. return nullptr;
  1167. return &window();
  1168. }
  1169. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#completely-finish-loading
  1170. void Document::completely_finish_loading()
  1171. {
  1172. // 1. Assert: document's browsing context is non-null.
  1173. VERIFY(browsing_context());
  1174. // FIXME: 2. Set document's completely loaded time to the current time.
  1175. // 3. Let container be document's browsing context's container.
  1176. auto* container = browsing_context()->container();
  1177. // 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.
  1178. if (container && is<HTML::HTMLIFrameElement>(*container)) {
  1179. container->queue_an_element_task(HTML::Task::Source::DOMManipulation, [container]() mutable {
  1180. run_iframe_load_event_steps(static_cast<HTML::HTMLIFrameElement&>(*container));
  1181. });
  1182. }
  1183. // 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.
  1184. else if (container) {
  1185. container->queue_an_element_task(HTML::Task::Source::DOMManipulation, [container]() mutable {
  1186. container->dispatch_event(DOM::Event::create(HTML::EventNames::load));
  1187. });
  1188. }
  1189. }
  1190. String Document::cookie(Cookie::Source source)
  1191. {
  1192. if (auto* page = this->page())
  1193. return page->client().page_did_request_cookie(m_url, source);
  1194. return {};
  1195. }
  1196. void Document::set_cookie(String const& cookie_string, Cookie::Source source)
  1197. {
  1198. auto cookie = Cookie::parse_cookie(cookie_string);
  1199. if (!cookie.has_value())
  1200. return;
  1201. if (auto* page = this->page())
  1202. page->client().page_did_set_cookie(m_url, cookie.value(), source);
  1203. }
  1204. String Document::dump_dom_tree_as_json() const
  1205. {
  1206. StringBuilder builder;
  1207. auto json = MUST(JsonObjectSerializer<>::try_create(builder));
  1208. serialize_tree_as_json(json);
  1209. MUST(json.finish());
  1210. return builder.to_string();
  1211. }
  1212. // https://html.spec.whatwg.org/multipage/semantics.html#has-a-style-sheet-that-is-blocking-scripts
  1213. bool Document::has_a_style_sheet_that_is_blocking_scripts() const
  1214. {
  1215. // A Document has a style sheet that is blocking scripts if its script-blocking style sheet counter is greater than 0,
  1216. if (m_script_blocking_style_sheet_counter > 0)
  1217. return true;
  1218. // ...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.
  1219. if (!browsing_context() || !browsing_context()->container_document())
  1220. return false;
  1221. return browsing_context()->container_document()->m_script_blocking_style_sheet_counter > 0;
  1222. }
  1223. String Document::referrer() const
  1224. {
  1225. return m_referrer;
  1226. }
  1227. void Document::set_referrer(String referrer)
  1228. {
  1229. m_referrer = referrer;
  1230. }
  1231. // https://html.spec.whatwg.org/multipage/browsers.html#fully-active
  1232. bool Document::is_fully_active() const
  1233. {
  1234. // 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,
  1235. // and either d's browsing context is a top-level browsing context, or d's browsing context's container document is fully active.
  1236. return browsing_context() && browsing_context()->active_document() == this && (browsing_context()->is_top_level() || browsing_context()->container_document()->is_fully_active());
  1237. }
  1238. // https://html.spec.whatwg.org/multipage/browsers.html#active-document
  1239. bool Document::is_active() const
  1240. {
  1241. // A browsing context's active document is its active window's associated Document.
  1242. return browsing_context() && browsing_context()->active_document() == this;
  1243. }
  1244. // https://html.spec.whatwg.org/multipage/history.html#dom-document-location
  1245. Bindings::LocationObject* Document::location()
  1246. {
  1247. // The Document object's location attribute's getter must return this Document object's relevant global object's Location object,
  1248. // if this Document object is fully active, and null otherwise.
  1249. if (!is_fully_active())
  1250. return nullptr;
  1251. return window().wrapper()->location_object();
  1252. }
  1253. // https://html.spec.whatwg.org/multipage/interaction.html#dom-document-hidden
  1254. bool Document::hidden() const
  1255. {
  1256. return false;
  1257. }
  1258. // https://html.spec.whatwg.org/multipage/interaction.html#dom-document-visibilitystate
  1259. String Document::visibility_state() const
  1260. {
  1261. return hidden() ? "hidden" : "visible";
  1262. }
  1263. // https://drafts.csswg.org/cssom-view/#run-the-resize-steps
  1264. void Document::run_the_resize_steps()
  1265. {
  1266. // 1. If doc’s viewport has had its width or height changed
  1267. // (e.g. as a result of the user resizing the browser window, or changing the page zoom scale factor,
  1268. // or an iframe element’s dimensions are changed) since the last time these steps were run,
  1269. // fire an event named resize at the Window object associated with doc.
  1270. if (!browsing_context())
  1271. return;
  1272. auto viewport_size = browsing_context()->viewport_rect().size();
  1273. if (m_last_viewport_size == viewport_size)
  1274. return;
  1275. m_last_viewport_size = viewport_size;
  1276. window().dispatch_event(DOM::Event::create(UIEvents::EventNames::resize));
  1277. update_layout();
  1278. }
  1279. void Document::add_media_query_list(NonnullRefPtr<CSS::MediaQueryList>& media_query_list)
  1280. {
  1281. m_media_query_lists.append(media_query_list);
  1282. }
  1283. // https://drafts.csswg.org/cssom-view/#evaluate-media-queries-and-report-changes
  1284. void Document::evaluate_media_queries_and_report_changes()
  1285. {
  1286. // NOTE: Not in the spec, but we take this opportunity to prune null WeakPtrs.
  1287. m_media_query_lists.remove_all_matching([](auto& it) {
  1288. return it.is_null();
  1289. });
  1290. // 1. For each MediaQueryList object target that has doc as its document,
  1291. // in the order they were created, oldest first, run these substeps:
  1292. for (auto& media_query_list_ptr : m_media_query_lists) {
  1293. // 1. If target’s matches state has changed since the last time these steps
  1294. // were run, fire an event at target using the MediaQueryListEvent constructor,
  1295. // with its type attribute initialized to change, its isTrusted attribute
  1296. // initialized to true, its media attribute initialized to target’s media,
  1297. // and its matches attribute initialized to target’s matches state.
  1298. if (media_query_list_ptr.is_null())
  1299. continue;
  1300. auto media_query_list = media_query_list_ptr.strong_ref();
  1301. bool did_match = media_query_list->matches();
  1302. bool now_matches = media_query_list->evaluate();
  1303. if (did_match != now_matches) {
  1304. CSS::MediaQueryListEventInit init;
  1305. init.media = media_query_list->media();
  1306. init.matches = now_matches;
  1307. auto event = CSS::MediaQueryListEvent::create(HTML::EventNames::change, init);
  1308. event->set_is_trusted(true);
  1309. media_query_list->dispatch_event(event);
  1310. }
  1311. }
  1312. // Also not in the spec, but this is as good a place as any to evaluate @media rules!
  1313. evaluate_media_rules();
  1314. }
  1315. void Document::evaluate_media_rules()
  1316. {
  1317. bool any_media_queries_changed_match_state = false;
  1318. for (auto& style_sheet : style_sheets().sheets()) {
  1319. if (style_sheet.evaluate_media_queries(window()))
  1320. any_media_queries_changed_match_state = true;
  1321. }
  1322. if (any_media_queries_changed_match_state) {
  1323. style_computer().invalidate_rule_cache();
  1324. invalidate_style();
  1325. }
  1326. }
  1327. NonnullRefPtr<DOMImplementation> Document::implementation() const
  1328. {
  1329. return *m_implementation;
  1330. }
  1331. bool Document::has_focus() const
  1332. {
  1333. // FIXME: Return whether we actually have focus.
  1334. return true;
  1335. }
  1336. void Document::set_parser(Badge<HTML::HTMLParser>, HTML::HTMLParser& parser)
  1337. {
  1338. m_parser = parser;
  1339. }
  1340. void Document::detach_parser(Badge<HTML::HTMLParser>)
  1341. {
  1342. m_parser = nullptr;
  1343. }
  1344. // https://www.w3.org/TR/xml/#NT-NameStartChar
  1345. static bool is_valid_name_start_character(u32 code_point)
  1346. {
  1347. return code_point == ':'
  1348. || (code_point >= 'A' && code_point <= 'Z')
  1349. || code_point == '_'
  1350. || (code_point >= 'a' && code_point <= 'z')
  1351. || (code_point >= 0xc0 && code_point <= 0xd6)
  1352. || (code_point >= 0xd8 && code_point <= 0xf6)
  1353. || (code_point >= 0xf8 && code_point <= 0x2ff)
  1354. || (code_point >= 0x370 && code_point <= 0x37d)
  1355. || (code_point >= 0x37f && code_point <= 0x1fff)
  1356. || (code_point >= 0x200c && code_point <= 0x200d)
  1357. || (code_point >= 0x2070 && code_point <= 0x218f)
  1358. || (code_point >= 0x2c00 && code_point <= 0x2fef)
  1359. || (code_point >= 0x3001 && code_point <= 0xD7ff)
  1360. || (code_point >= 0xf900 && code_point <= 0xfdcf)
  1361. || (code_point >= 0xfdf0 && code_point <= 0xfffd)
  1362. || (code_point >= 0x10000 && code_point <= 0xeffff);
  1363. }
  1364. // https://www.w3.org/TR/xml/#NT-NameChar
  1365. static inline bool is_valid_name_character(u32 code_point)
  1366. {
  1367. return is_valid_name_start_character(code_point)
  1368. || code_point == '-'
  1369. || code_point == '.'
  1370. || (code_point >= '0' && code_point <= '9')
  1371. || code_point == 0xb7
  1372. || (code_point >= 0x300 && code_point <= 0x36f)
  1373. || (code_point >= 0x203f && code_point <= 0x2040);
  1374. }
  1375. bool Document::is_valid_name(String const& name)
  1376. {
  1377. if (name.is_empty())
  1378. return false;
  1379. if (!is_valid_name_start_character(name[0]))
  1380. return false;
  1381. for (size_t i = 1; i < name.length(); ++i) {
  1382. if (!is_valid_name_character(name[i]))
  1383. return false;
  1384. }
  1385. return true;
  1386. }
  1387. // https://dom.spec.whatwg.org/#validate
  1388. ExceptionOr<Document::PrefixAndTagName> Document::validate_qualified_name(String const& qualified_name)
  1389. {
  1390. if (qualified_name.is_empty())
  1391. return InvalidCharacterError::create("Empty string is not a valid qualified name.");
  1392. Utf8View utf8view { qualified_name };
  1393. if (!utf8view.validate())
  1394. return InvalidCharacterError::create("Invalid qualified name.");
  1395. Optional<size_t> colon_offset;
  1396. bool at_start_of_name = true;
  1397. for (auto it = utf8view.begin(); it != utf8view.end(); ++it) {
  1398. auto code_point = *it;
  1399. if (code_point == ':') {
  1400. if (colon_offset.has_value())
  1401. return InvalidCharacterError::create("More than one colon (:) in qualified name.");
  1402. colon_offset = utf8view.byte_offset_of(it);
  1403. at_start_of_name = true;
  1404. continue;
  1405. }
  1406. if (at_start_of_name) {
  1407. if (!is_valid_name_start_character(code_point))
  1408. return InvalidCharacterError::create("Invalid start of qualified name.");
  1409. at_start_of_name = false;
  1410. continue;
  1411. }
  1412. if (!is_valid_name_character(code_point))
  1413. return InvalidCharacterError::create("Invalid character in qualified name.");
  1414. }
  1415. if (!colon_offset.has_value())
  1416. return Document::PrefixAndTagName {
  1417. .prefix = {},
  1418. .tag_name = qualified_name,
  1419. };
  1420. if (*colon_offset == 0)
  1421. return InvalidCharacterError::create("Qualified name can't start with colon (:).");
  1422. if (*colon_offset >= (qualified_name.length() - 1))
  1423. return InvalidCharacterError::create("Qualified name can't end with colon (:).");
  1424. return Document::PrefixAndTagName {
  1425. .prefix = qualified_name.substring_view(0, *colon_offset),
  1426. .tag_name = qualified_name.substring_view(*colon_offset + 1),
  1427. };
  1428. }
  1429. // https://dom.spec.whatwg.org/#dom-document-createnodeiterator
  1430. NonnullRefPtr<NodeIterator> Document::create_node_iterator(Node& root, unsigned what_to_show, RefPtr<NodeFilter> filter)
  1431. {
  1432. return NodeIterator::create(root, what_to_show, move(filter));
  1433. }
  1434. // https://dom.spec.whatwg.org/#dom-document-createtreewalker
  1435. NonnullRefPtr<TreeWalker> Document::create_tree_walker(Node& root, unsigned what_to_show, RefPtr<NodeFilter> filter)
  1436. {
  1437. return TreeWalker::create(root, what_to_show, move(filter));
  1438. }
  1439. void Document::register_node_iterator(Badge<NodeIterator>, NodeIterator& node_iterator)
  1440. {
  1441. auto result = m_node_iterators.set(&node_iterator);
  1442. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  1443. }
  1444. void Document::unregister_node_iterator(Badge<NodeIterator>, NodeIterator& node_iterator)
  1445. {
  1446. bool was_removed = m_node_iterators.remove(&node_iterator);
  1447. VERIFY(was_removed);
  1448. }
  1449. void Document::increment_number_of_things_delaying_the_load_event(Badge<DocumentLoadEventDelayer>)
  1450. {
  1451. ++m_number_of_things_delaying_the_load_event;
  1452. if (auto* page = this->page())
  1453. page->client().page_did_update_resource_count(m_number_of_things_delaying_the_load_event);
  1454. }
  1455. void Document::decrement_number_of_things_delaying_the_load_event(Badge<DocumentLoadEventDelayer>)
  1456. {
  1457. VERIFY(m_number_of_things_delaying_the_load_event);
  1458. --m_number_of_things_delaying_the_load_event;
  1459. if (auto* page = this->page())
  1460. page->client().page_did_update_resource_count(m_number_of_things_delaying_the_load_event);
  1461. }
  1462. void Document::invalidate_stacking_context_tree()
  1463. {
  1464. if (auto* paint_box = this->paint_box())
  1465. const_cast<Painting::PaintableBox*>(paint_box)->invalidate_stacking_context();
  1466. }
  1467. void Document::check_favicon_after_loading_link_resource()
  1468. {
  1469. // https://html.spec.whatwg.org/multipage/links.html#rel-icon
  1470. // NOTE: firefox also load favicons outside the head tag, which is against spec (see table 4.6.7)
  1471. auto head_element = head();
  1472. auto favicon_link_elements = HTMLCollection::create(*head_element, [](Element const& element) {
  1473. if (!is<HTML::HTMLLinkElement>(element))
  1474. return false;
  1475. return static_cast<HTML::HTMLLinkElement const&>(element).has_loaded_icon();
  1476. });
  1477. if (favicon_link_elements->length() == 0) {
  1478. dbgln_if(SPAM_DEBUG, "No favicon found to be used");
  1479. return;
  1480. }
  1481. // 4.6.7.8 Link type "icon"
  1482. //
  1483. // If there are multiple equally appropriate icons, user agents must use the last one declared
  1484. // in tree order at the time that the user agent collected the list of icons.
  1485. //
  1486. // If multiple icons are provided, the user agent must select the most appropriate icon
  1487. // according to the type, media, and sizes attributes.
  1488. //
  1489. // FIXME: There is no selective behavior yet for favicons.
  1490. for (auto i = favicon_link_elements->length(); i-- > 0;) {
  1491. auto favicon_element = favicon_link_elements->item(i);
  1492. if (favicon_element == m_active_element)
  1493. return;
  1494. // If the user agent tries to use an icon but that icon is determined, upon closer examination,
  1495. // to in fact be inappropriate (...), then the user agent must try the next-most-appropriate icon
  1496. // as determined by the attributes.
  1497. if (static_cast<HTML::HTMLLinkElement*>(favicon_element)->load_favicon_and_use_if_window_is_active()) {
  1498. m_active_favicon = favicon_element;
  1499. return;
  1500. }
  1501. }
  1502. dbgln_if(SPAM_DEBUG, "No favicon found to be used");
  1503. }
  1504. void Document::set_window(Badge<HTML::BrowsingContext>, HTML::Window& window)
  1505. {
  1506. m_window = window;
  1507. }
  1508. Bindings::WindowObject& Document::preferred_window_object() const
  1509. {
  1510. if (m_window && m_window->wrapper())
  1511. return const_cast<Bindings::WindowObject&>(*m_window->wrapper());
  1512. return Bindings::main_thread_internal_window_object();
  1513. }
  1514. }