Document.cpp 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876
  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 <LibJS/Interpreter.h>
  13. #include <LibJS/Parser.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/DOMException.h>
  23. #include <LibWeb/DOM/DOMImplementation.h>
  24. #include <LibWeb/DOM/Document.h>
  25. #include <LibWeb/DOM/DocumentFragment.h>
  26. #include <LibWeb/DOM/DocumentType.h>
  27. #include <LibWeb/DOM/Element.h>
  28. #include <LibWeb/DOM/ElementFactory.h>
  29. #include <LibWeb/DOM/Event.h>
  30. #include <LibWeb/DOM/ExceptionOr.h>
  31. #include <LibWeb/DOM/HTMLCollection.h>
  32. #include <LibWeb/DOM/NodeIterator.h>
  33. #include <LibWeb/DOM/Range.h>
  34. #include <LibWeb/DOM/ShadowRoot.h>
  35. #include <LibWeb/DOM/Text.h>
  36. #include <LibWeb/DOM/TreeWalker.h>
  37. #include <LibWeb/Dump.h>
  38. #include <LibWeb/HTML/AttributeNames.h>
  39. #include <LibWeb/HTML/BrowsingContext.h>
  40. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  41. #include <LibWeb/HTML/EventNames.h>
  42. #include <LibWeb/HTML/HTMLAnchorElement.h>
  43. #include <LibWeb/HTML/HTMLAreaElement.h>
  44. #include <LibWeb/HTML/HTMLBaseElement.h>
  45. #include <LibWeb/HTML/HTMLBodyElement.h>
  46. #include <LibWeb/HTML/HTMLEmbedElement.h>
  47. #include <LibWeb/HTML/HTMLFormElement.h>
  48. #include <LibWeb/HTML/HTMLFrameSetElement.h>
  49. #include <LibWeb/HTML/HTMLHeadElement.h>
  50. #include <LibWeb/HTML/HTMLHtmlElement.h>
  51. #include <LibWeb/HTML/HTMLIFrameElement.h>
  52. #include <LibWeb/HTML/HTMLImageElement.h>
  53. #include <LibWeb/HTML/HTMLLinkElement.h>
  54. #include <LibWeb/HTML/HTMLScriptElement.h>
  55. #include <LibWeb/HTML/HTMLTitleElement.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/Layout/BlockFormattingContext.h>
  64. #include <LibWeb/Layout/InitialContainingBlock.h>
  65. #include <LibWeb/Layout/TreeBuilder.h>
  66. #include <LibWeb/Namespace.h>
  67. #include <LibWeb/Page/Page.h>
  68. #include <LibWeb/Platform/Timer.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-plurs-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. JS::NonnullGCPtr<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. JS::GCPtr<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::Object* {
  150. // - For the global object, create a new Window object.
  151. window = HTML::Window::create(realm);
  152. return window;
  153. },
  154. [](JS::Realm&) -> JS::Object* {
  155. // FIXME: - For the global this binding, use browsingContext's WindowProxy object.
  156. return nullptr;
  157. });
  158. // 6. Let topLevelCreationURL be creationURL.
  159. auto top_level_creation_url = creation_url;
  160. // 7. Let topLevelOrigin be navigationParams's origin.
  161. auto top_level_origin = navigation_params.origin;
  162. // 8. If browsingContext is not a top-level browsing context, then:
  163. if (!browsing_context->is_top_level()) {
  164. // 1. Let parentEnvironment be browsingContext's container's relevant settings object.
  165. VERIFY(browsing_context->container());
  166. auto& parent_environment = HTML::relevant_settings_object(*browsing_context->container());
  167. // 2. Set topLevelCreationURL to parentEnvironment's top-level creation URL.
  168. top_level_creation_url = parent_environment.top_level_creation_url;
  169. // 3. Set topLevelOrigin to parentEnvironment's top-level origin.
  170. top_level_origin = parent_environment.top_level_origin;
  171. }
  172. // 9. Set up a window environment settings object with creationURL, realm execution context,
  173. // navigationParams's reserved environment, topLevelCreationURL, and topLevelOrigin.
  174. // FIXME: Why do we assume `creation_url` is non-empty here? Is this a spec bug?
  175. // FIXME: Why do we assume `top_level_creation_url` is non-empty here? Is this a spec bug?
  176. HTML::WindowEnvironmentSettingsObject::setup(
  177. creation_url.value(),
  178. move(realm_execution_context),
  179. navigation_params.reserved_environment,
  180. top_level_creation_url.value(),
  181. top_level_origin);
  182. }
  183. // 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.
  184. // 8. Let document be a new Document,
  185. // whose type is type,
  186. // content type is contentType,
  187. // origin is navigationParams's origin,
  188. // FIXME: policy container is navigationParams's policy container,
  189. // FIXME: permissions policy is permissionsPolicy,
  190. // FIXME: active sandboxing flag set is navigationParams's final sandboxing flag set,
  191. // FIXME: and cross-origin opener policy is navigationParams's cross-origin opener policy,
  192. // FIXME: load timing info is loadTimingInfo,
  193. // FIXME: and navigation id is navigationParams's id.
  194. auto document = Document::create(*window);
  195. document->m_type = type;
  196. document->m_content_type = content_type;
  197. document->set_origin(navigation_params.origin);
  198. document->m_window = window;
  199. window->set_associated_document(*document);
  200. // 9. Set document's URL to creationURL.
  201. document->m_url = creation_url.value();
  202. // 10. Set document's current document readiness to "loading".
  203. document->m_readiness = HTML::DocumentReadyState::Loading;
  204. // FIXME: 11. Run CSP initialization for a Document given document.
  205. // 12. If navigationParams's request is non-null, then:
  206. if (navigation_params.request) {
  207. // FIXME: 1. Set document's referrer to the empty string.
  208. // FIXME: 2. Let referrer be navigationParams's request's referrer.
  209. // FIXME: 3. If referrer is a URL record, then set document's referrer to the serialization of referrer.
  210. }
  211. // FIXME: 13. Let historyHandling be navigationParams's history handling.
  212. // FIXME: 14: Let navigationTimingType be the result of switching on navigationParams's history handling...
  213. // FIXME: 15. Let redirectCount be 0 if navigationParams's has cross-origin redirects is true;
  214. // otherwise navigationParams's request's redirect count.
  215. // FIXME: 16. Create the navigation timing entry for document, with navigationParams's response's timing info,
  216. // redirectCount, navigationTimingType, and navigationParams's response's service worker timing info.
  217. // FIXME: 17. If navigationParams's response has a `Refresh` header, then...
  218. // FIXME: 18. If navigationParams's commit early hints is not null, then call navigationParams's commit early hints with document.
  219. // FIXME: 19. Process link headers given document, navigationParams's response, and "pre-media".
  220. // 20. Return document.
  221. return document;
  222. }
  223. JS::NonnullGCPtr<Document> Document::create_with_global_object(HTML::Window& window)
  224. {
  225. return Document::create(window);
  226. }
  227. JS::NonnullGCPtr<Document> Document::create(HTML::Window& window, AK::URL const& url)
  228. {
  229. auto& realm = window.realm();
  230. return *realm.heap().allocate<Document>(realm, window, url);
  231. }
  232. Document::Document(HTML::Window& window, const AK::URL& url)
  233. : ParentNode(window.realm(), *this, NodeType::DOCUMENT_NODE)
  234. , m_style_computer(make<CSS::StyleComputer>(*this))
  235. , m_url(url)
  236. , m_window(window)
  237. {
  238. set_prototype(&window.cached_web_prototype("Document"));
  239. HTML::main_thread_event_loop().register_document({}, *this);
  240. m_style_update_timer = Platform::Timer::create_single_shot(0, [this] {
  241. update_style();
  242. });
  243. m_layout_update_timer = Platform::Timer::create_single_shot(0, [this] {
  244. force_layout();
  245. });
  246. }
  247. Document::~Document()
  248. {
  249. HTML::main_thread_event_loop().unregister_document({}, *this);
  250. }
  251. void Document::visit_edges(Cell::Visitor& visitor)
  252. {
  253. Base::visit_edges(visitor);
  254. visitor.visit(m_window.ptr());
  255. visitor.visit(m_style_sheets.ptr());
  256. visitor.visit(m_hovered_node.ptr());
  257. visitor.visit(m_inspected_node.ptr());
  258. visitor.visit(m_active_favicon.ptr());
  259. visitor.visit(m_focused_element.ptr());
  260. visitor.visit(m_active_element.ptr());
  261. visitor.visit(m_implementation.ptr());
  262. visitor.visit(m_current_script.ptr());
  263. visitor.visit(m_associated_inert_template_document.ptr());
  264. visitor.visit(m_pending_parsing_blocking_script.ptr());
  265. visitor.visit(m_history.ptr());
  266. for (auto& script : m_scripts_to_execute_when_parsing_has_finished)
  267. visitor.visit(script.ptr());
  268. for (auto& script : m_scripts_to_execute_as_soon_as_possible)
  269. visitor.visit(script.ptr());
  270. for (auto& node_iterator : m_node_iterators)
  271. visitor.visit(node_iterator);
  272. }
  273. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-write
  274. ExceptionOr<void> Document::write(Vector<String> const& strings)
  275. {
  276. StringBuilder builder;
  277. builder.join(""sv, strings);
  278. return run_the_document_write_steps(builder.build());
  279. }
  280. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-writeln
  281. ExceptionOr<void> Document::writeln(Vector<String> const& strings)
  282. {
  283. StringBuilder builder;
  284. builder.join(""sv, strings);
  285. builder.append("\n"sv);
  286. return run_the_document_write_steps(builder.build());
  287. }
  288. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#document-write-steps
  289. ExceptionOr<void> Document::run_the_document_write_steps(String input)
  290. {
  291. // 1. If document is an XML document, then throw an "InvalidStateError" DOMException.
  292. if (m_type == Type::XML)
  293. return DOM::InvalidStateError::create(global_object(), "write() called on XML document.");
  294. // 2. If document's throw-on-dynamic-markup-insertion counter is greater than 0, then throw an "InvalidStateError" DOMException.
  295. if (m_throw_on_dynamic_markup_insertion_counter > 0)
  296. return DOM::InvalidStateError::create(global_object(), "throw-on-dynamic-markup-insertion-counter greater than zero.");
  297. // 3. If document's active parser was aborted is true, then return.
  298. if (m_active_parser_was_aborted)
  299. return {};
  300. // 4. If the insertion point is undefined, then:
  301. if (!(m_parser && m_parser->tokenizer().is_insertion_point_defined())) {
  302. // 1. If document's unload counter is greater than 0 or document's ignore-destructive-writes counter is greater than 0, then return.
  303. if (m_unload_counter > 0 || m_ignore_destructive_writes_counter > 0)
  304. return {};
  305. // 2. Run the document open steps with document.
  306. open();
  307. }
  308. // 5. Insert input into the input stream just before the insertion point.
  309. m_parser->tokenizer().insert_input_at_insertion_point(input);
  310. // 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).
  311. if (!pending_parsing_blocking_script())
  312. m_parser->run();
  313. return {};
  314. }
  315. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-open
  316. ExceptionOr<Document*> Document::open(String const&, String const&)
  317. {
  318. // 1. If document is an XML document, then throw an "InvalidStateError" DOMException exception.
  319. if (m_type == Type::XML)
  320. return DOM::InvalidStateError::create(global_object(), "open() called on XML document.");
  321. // 2. If document's throw-on-dynamic-markup-insertion counter is greater than 0, then throw an "InvalidStateError" DOMException.
  322. if (m_throw_on_dynamic_markup_insertion_counter > 0)
  323. return DOM::InvalidStateError::create(global_object(), "throw-on-dynamic-markup-insertion-counter greater than zero.");
  324. // FIXME: 3. Let entryDocument be the entry global object's associated Document.
  325. auto& entry_document = *this;
  326. // 4. If document's origin is not same origin to entryDocument's origin, then throw a "SecurityError" DOMException.
  327. if (origin() != entry_document.origin())
  328. return DOM::SecurityError::create(global_object(), "Document.origin() not the same as entryDocument's.");
  329. // 5. If document has an active parser whose script nesting level is greater than 0, then return document.
  330. if (m_parser && m_parser->script_nesting_level() > 0)
  331. return this;
  332. // 6. Similarly, if document's unload counter is greater than 0, then return document.
  333. if (m_unload_counter > 0)
  334. return this;
  335. // 7. If document's active parser was aborted is true, then return document.
  336. if (m_active_parser_was_aborted)
  337. return this;
  338. // 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.
  339. // FIXME: 9. For each shadow-including inclusive descendant node of document, erase all event listeners and handlers given node.
  340. // 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.
  341. // 11. Replace all with null within document, without firing any mutation events.
  342. replace_all(nullptr);
  343. // 12. If document is fully active, then:
  344. if (is_fully_active()) {
  345. // 1. Let newURL be a copy of entryDocument's URL.
  346. auto new_url = entry_document.url();
  347. // 2. If entryDocument is not document, then set newURL's fragment to null.
  348. if (&entry_document != this)
  349. new_url.set_fragment("");
  350. // FIXME: 3. Run the URL and history update steps with document and newURL.
  351. }
  352. // 13. Set document's is initial about:blank to false.
  353. set_is_initial_about_blank(false);
  354. // FIXME: 14. If document's iframe load in progress flag is set, then set document's mute iframe load flag.
  355. // 15. Set document to no-quirks mode.
  356. set_quirks_mode(QuirksMode::No);
  357. // 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.
  358. m_parser = HTML::HTMLParser::create_for_scripting(*this);
  359. // 17. Set the insertion point to point at just before the end of the input stream (which at this point will be empty).
  360. m_parser->tokenizer().update_insertion_point();
  361. // 18. Update the current document readiness of document to "loading".
  362. update_readiness(HTML::DocumentReadyState::Loading);
  363. // 19. Return document.
  364. return this;
  365. }
  366. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#closing-the-input-stream
  367. ExceptionOr<void> Document::close()
  368. {
  369. // 1. If document is an XML document, then throw an "InvalidStateError" DOMException exception.
  370. if (m_type == Type::XML)
  371. return DOM::InvalidStateError::create(global_object(), "close() called on XML document.");
  372. // 2. If document's throw-on-dynamic-markup-insertion counter is greater than 0, then throw an "InvalidStateError" DOMException.
  373. if (m_throw_on_dynamic_markup_insertion_counter > 0)
  374. return DOM::InvalidStateError::create(global_object(), "throw-on-dynamic-markup-insertion-counter greater than zero.");
  375. // 3. If there is no script-created parser associated with the document, then return.
  376. if (!m_parser)
  377. return {};
  378. // FIXME: 4. Insert an explicit "EOF" character at the end of the parser's input stream.
  379. m_parser->tokenizer().insert_eof();
  380. // 5. If there is a pending parsing-blocking script, then return.
  381. if (pending_parsing_blocking_script())
  382. return {};
  383. // 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.
  384. m_parser->run();
  385. return {};
  386. }
  387. HTML::Origin Document::origin() const
  388. {
  389. return m_origin;
  390. }
  391. void Document::set_origin(HTML::Origin const& origin)
  392. {
  393. m_origin = origin;
  394. }
  395. void Document::schedule_style_update()
  396. {
  397. if (m_style_update_timer->is_active())
  398. return;
  399. m_style_update_timer->start();
  400. }
  401. void Document::schedule_layout_update()
  402. {
  403. if (m_layout_update_timer->is_active())
  404. return;
  405. m_layout_update_timer->start();
  406. }
  407. bool Document::is_child_allowed(Node const& node) const
  408. {
  409. switch (node.type()) {
  410. case NodeType::DOCUMENT_NODE:
  411. case NodeType::TEXT_NODE:
  412. return false;
  413. case NodeType::COMMENT_NODE:
  414. return true;
  415. case NodeType::DOCUMENT_TYPE_NODE:
  416. return !first_child_of_type<DocumentType>();
  417. case NodeType::ELEMENT_NODE:
  418. return !first_child_of_type<Element>();
  419. default:
  420. return false;
  421. }
  422. }
  423. Element* Document::document_element()
  424. {
  425. return first_child_of_type<Element>();
  426. }
  427. Element const* Document::document_element() const
  428. {
  429. return first_child_of_type<Element>();
  430. }
  431. HTML::HTMLHtmlElement* Document::html_element()
  432. {
  433. auto* html = document_element();
  434. if (is<HTML::HTMLHtmlElement>(html))
  435. return verify_cast<HTML::HTMLHtmlElement>(html);
  436. return nullptr;
  437. }
  438. HTML::HTMLHeadElement* Document::head()
  439. {
  440. auto* html = html_element();
  441. if (!html)
  442. return nullptr;
  443. return html->first_child_of_type<HTML::HTMLHeadElement>();
  444. }
  445. HTML::HTMLElement* Document::body()
  446. {
  447. auto* html = html_element();
  448. if (!html)
  449. return nullptr;
  450. auto* first_body = html->first_child_of_type<HTML::HTMLBodyElement>();
  451. if (first_body)
  452. return first_body;
  453. auto* first_frameset = html->first_child_of_type<HTML::HTMLFrameSetElement>();
  454. if (first_frameset)
  455. return first_frameset;
  456. return nullptr;
  457. }
  458. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-body
  459. ExceptionOr<void> Document::set_body(HTML::HTMLElement* new_body)
  460. {
  461. if (!is<HTML::HTMLBodyElement>(new_body) && !is<HTML::HTMLFrameSetElement>(new_body))
  462. return DOM::HierarchyRequestError::create(global_object(), "Invalid document body element, must be 'body' or 'frameset'");
  463. auto* existing_body = body();
  464. if (existing_body) {
  465. (void)TRY(existing_body->parent()->replace_child(*new_body, *existing_body));
  466. return {};
  467. }
  468. auto* document_element = this->document_element();
  469. if (!document_element)
  470. return DOM::HierarchyRequestError::create(global_object(), "Missing document element");
  471. (void)TRY(document_element->append_child(*new_body));
  472. return {};
  473. }
  474. String Document::title() const
  475. {
  476. auto* head_element = head();
  477. if (!head_element)
  478. return {};
  479. auto* title_element = head_element->first_child_of_type<HTML::HTMLTitleElement>();
  480. if (!title_element)
  481. return {};
  482. auto raw_title = title_element->text_content();
  483. StringBuilder builder;
  484. bool last_was_space = false;
  485. for (auto code_point : Utf8View(raw_title)) {
  486. if (is_ascii_space(code_point)) {
  487. last_was_space = true;
  488. } else {
  489. if (last_was_space && !builder.is_empty())
  490. builder.append(' ');
  491. builder.append_code_point(code_point);
  492. last_was_space = false;
  493. }
  494. }
  495. return builder.to_string();
  496. }
  497. void Document::set_title(String const& title)
  498. {
  499. auto* head_element = const_cast<HTML::HTMLHeadElement*>(head());
  500. if (!head_element)
  501. return;
  502. JS::GCPtr<HTML::HTMLTitleElement> title_element = head_element->first_child_of_type<HTML::HTMLTitleElement>();
  503. if (!title_element) {
  504. title_element = &static_cast<HTML::HTMLTitleElement&>(*create_element(HTML::TagNames::title).release_value());
  505. head_element->append_child(*title_element);
  506. }
  507. title_element->remove_all_children(true);
  508. title_element->append_child(*heap().allocate<Text>(realm(), *this, title));
  509. if (auto* page = this->page()) {
  510. if (browsing_context() == &page->top_level_browsing_context())
  511. page->client().page_did_change_title(title);
  512. }
  513. }
  514. void Document::attach_to_browsing_context(Badge<HTML::BrowsingContext>, HTML::BrowsingContext& browsing_context)
  515. {
  516. m_browsing_context = browsing_context;
  517. }
  518. void Document::detach_from_browsing_context(Badge<HTML::BrowsingContext>, HTML::BrowsingContext& browsing_context)
  519. {
  520. VERIFY(&browsing_context == m_browsing_context);
  521. tear_down_layout_tree();
  522. m_browsing_context = nullptr;
  523. }
  524. void Document::tear_down_layout_tree()
  525. {
  526. if (!m_layout_root)
  527. return;
  528. // Gather up all the layout nodes in a vector and detach them from parents
  529. // while the vector keeps them alive.
  530. NonnullRefPtrVector<Layout::Node> layout_nodes;
  531. m_layout_root->for_each_in_inclusive_subtree([&](auto& layout_node) {
  532. layout_nodes.append(layout_node);
  533. return IterationDecision::Continue;
  534. });
  535. for (auto& layout_node : layout_nodes) {
  536. if (layout_node.parent())
  537. layout_node.parent()->remove_child(layout_node);
  538. }
  539. m_layout_root = nullptr;
  540. }
  541. Color Document::background_color(Gfx::Palette const& palette) const
  542. {
  543. // CSS2 says we should use the HTML element's background color unless it's transparent...
  544. if (auto* html_element = this->html_element(); html_element && html_element->layout_node()) {
  545. auto color = html_element->layout_node()->computed_values().background_color();
  546. if (color.alpha())
  547. return color;
  548. }
  549. // ...in which case we use the BODY element's background color.
  550. if (auto* body_element = body(); body_element && body_element->layout_node()) {
  551. auto color = body_element->layout_node()->computed_values().background_color();
  552. if (color.alpha())
  553. return color;
  554. }
  555. // If both HTML and BODY are transparent, we fall back to the system's "base" palette color.
  556. return palette.base();
  557. }
  558. Vector<CSS::BackgroundLayerData> const* Document::background_layers() const
  559. {
  560. auto* body_element = body();
  561. if (!body_element)
  562. return {};
  563. auto* body_layout_node = body_element->layout_node();
  564. if (!body_layout_node)
  565. return {};
  566. return &body_layout_node->background_layers();
  567. }
  568. JS::GCPtr<HTML::HTMLBaseElement> Document::first_base_element_with_href_in_tree_order() const
  569. {
  570. JS::GCPtr<HTML::HTMLBaseElement> base_element;
  571. for_each_in_subtree_of_type<HTML::HTMLBaseElement>([&base_element](HTML::HTMLBaseElement const& base_element_in_tree) {
  572. if (base_element_in_tree.has_attribute(HTML::AttributeNames::href)) {
  573. base_element = &base_element_in_tree;
  574. return IterationDecision::Break;
  575. }
  576. return IterationDecision::Continue;
  577. });
  578. return base_element;
  579. }
  580. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#fallback-base-url
  581. AK::URL Document::fallback_base_url() const
  582. {
  583. // FIXME: 1. If document is an iframe srcdoc document, then return the document base URL of document's browsing context's container document.
  584. // 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.
  585. // 3. Return document's URL.
  586. return m_url;
  587. }
  588. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#document-base-url
  589. AK::URL Document::base_url() const
  590. {
  591. // 1. If there is no base element that has an href attribute in the Document, then return the Document's fallback base URL.
  592. auto base_element = first_base_element_with_href_in_tree_order();
  593. if (!base_element)
  594. return fallback_base_url();
  595. // 2. Otherwise, return the frozen base URL of the first base element in the Document that has an href attribute, in tree order.
  596. return base_element->frozen_base_url();
  597. }
  598. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#parse-a-url
  599. AK::URL Document::parse_url(String const& url) const
  600. {
  601. // FIXME: Pass in document's character encoding.
  602. return base_url().complete_url(url);
  603. }
  604. void Document::set_needs_layout()
  605. {
  606. if (m_needs_layout)
  607. return;
  608. m_needs_layout = true;
  609. schedule_layout_update();
  610. }
  611. void Document::force_layout()
  612. {
  613. tear_down_layout_tree();
  614. update_layout();
  615. }
  616. void Document::invalidate_layout()
  617. {
  618. tear_down_layout_tree();
  619. schedule_layout_update();
  620. }
  621. void Document::update_layout()
  622. {
  623. // NOTE: If our parent document needs a relayout, we must do that *first*.
  624. // This is necessary as the parent layout may cause our viewport to change.
  625. if (browsing_context() && browsing_context()->container())
  626. browsing_context()->container()->document().update_layout();
  627. update_style();
  628. if (!m_needs_layout && m_layout_root)
  629. return;
  630. if (!browsing_context())
  631. return;
  632. auto viewport_rect = browsing_context()->viewport_rect();
  633. if (!m_layout_root) {
  634. m_next_layout_node_serial_id = 0;
  635. Layout::TreeBuilder tree_builder;
  636. m_layout_root = static_ptr_cast<Layout::InitialContainingBlock>(tree_builder.build(*this));
  637. }
  638. Layout::LayoutState layout_state;
  639. layout_state.used_values_per_layout_node.resize(layout_node_count());
  640. {
  641. Layout::BlockFormattingContext root_formatting_context(layout_state, *m_layout_root, nullptr);
  642. auto& icb = static_cast<Layout::InitialContainingBlock&>(*m_layout_root);
  643. auto& icb_state = layout_state.get_mutable(icb);
  644. icb_state.set_has_definite_width(true);
  645. icb_state.set_has_definite_height(true);
  646. icb_state.set_content_width(viewport_rect.width());
  647. icb_state.set_content_height(viewport_rect.height());
  648. root_formatting_context.run(*m_layout_root, Layout::LayoutMode::Normal);
  649. }
  650. layout_state.commit();
  651. browsing_context()->set_needs_display();
  652. if (browsing_context()->is_top_level()) {
  653. if (auto* page = this->page())
  654. page->client().page_did_layout();
  655. }
  656. m_needs_layout = false;
  657. m_layout_update_timer->stop();
  658. }
  659. [[nodiscard]] static bool update_style_recursively(DOM::Node& node)
  660. {
  661. bool const needs_full_style_update = node.document().needs_full_style_update();
  662. bool needs_relayout = false;
  663. if (is<Element>(node)) {
  664. needs_relayout |= static_cast<Element&>(node).recompute_style() == Element::NeedsRelayout::Yes;
  665. }
  666. node.set_needs_style_update(false);
  667. if (needs_full_style_update || node.child_needs_style_update()) {
  668. if (node.is_element()) {
  669. if (auto* shadow_root = static_cast<DOM::Element&>(node).shadow_root()) {
  670. if (needs_full_style_update || shadow_root->needs_style_update() || shadow_root->child_needs_style_update())
  671. needs_relayout |= update_style_recursively(*shadow_root);
  672. }
  673. }
  674. node.for_each_child([&](auto& child) {
  675. if (needs_full_style_update || child.needs_style_update() || child.child_needs_style_update())
  676. needs_relayout |= update_style_recursively(child);
  677. return IterationDecision::Continue;
  678. });
  679. }
  680. node.set_child_needs_style_update(false);
  681. return needs_relayout;
  682. }
  683. void Document::update_style()
  684. {
  685. if (!browsing_context())
  686. return;
  687. if (!needs_full_style_update() && !needs_style_update() && !child_needs_style_update())
  688. return;
  689. evaluate_media_rules();
  690. if (update_style_recursively(*this))
  691. invalidate_layout();
  692. m_needs_full_style_update = false;
  693. m_style_update_timer->stop();
  694. }
  695. void Document::set_link_color(Color color)
  696. {
  697. m_link_color = color;
  698. }
  699. void Document::set_active_link_color(Color color)
  700. {
  701. m_active_link_color = color;
  702. }
  703. void Document::set_visited_link_color(Color color)
  704. {
  705. m_visited_link_color = color;
  706. }
  707. Layout::InitialContainingBlock const* Document::layout_node() const
  708. {
  709. return static_cast<Layout::InitialContainingBlock const*>(Node::layout_node());
  710. }
  711. Layout::InitialContainingBlock* Document::layout_node()
  712. {
  713. return static_cast<Layout::InitialContainingBlock*>(Node::layout_node());
  714. }
  715. void Document::set_inspected_node(Node* node)
  716. {
  717. if (m_inspected_node.ptr() == node)
  718. return;
  719. if (m_inspected_node && m_inspected_node->layout_node())
  720. m_inspected_node->layout_node()->set_needs_display();
  721. m_inspected_node = node;
  722. if (m_inspected_node && m_inspected_node->layout_node())
  723. m_inspected_node->layout_node()->set_needs_display();
  724. }
  725. static Node* find_common_ancestor(Node* a, Node* b)
  726. {
  727. if (!a || !b)
  728. return nullptr;
  729. if (a == b)
  730. return a;
  731. HashTable<Node*> ancestors;
  732. for (auto* node = a; node; node = node->parent_or_shadow_host())
  733. ancestors.set(node);
  734. for (auto* node = b; node; node = node->parent_or_shadow_host()) {
  735. if (ancestors.contains(node))
  736. return node;
  737. }
  738. return nullptr;
  739. }
  740. void Document::set_hovered_node(Node* node)
  741. {
  742. if (m_hovered_node.ptr() == node)
  743. return;
  744. JS::GCPtr<Node> old_hovered_node = move(m_hovered_node);
  745. m_hovered_node = node;
  746. if (auto* common_ancestor = find_common_ancestor(old_hovered_node, m_hovered_node))
  747. common_ancestor->invalidate_style();
  748. else
  749. invalidate_style();
  750. }
  751. JS::NonnullGCPtr<HTMLCollection> Document::get_elements_by_name(String const& name)
  752. {
  753. return HTMLCollection::create(*this, [name](Element const& element) {
  754. return element.name() == name;
  755. });
  756. }
  757. JS::NonnullGCPtr<HTMLCollection> Document::get_elements_by_class_name(FlyString const& class_names)
  758. {
  759. Vector<FlyString> list_of_class_names;
  760. for (auto& name : class_names.view().split_view(' ')) {
  761. list_of_class_names.append(name);
  762. }
  763. return HTMLCollection::create(*this, [list_of_class_names = move(list_of_class_names), quirks_mode = document().in_quirks_mode()](Element const& element) {
  764. for (auto& name : list_of_class_names) {
  765. if (!element.has_class(name, quirks_mode ? CaseSensitivity::CaseInsensitive : CaseSensitivity::CaseSensitive))
  766. return false;
  767. }
  768. return true;
  769. });
  770. }
  771. // https://html.spec.whatwg.org/multipage/obsolete.html#dom-document-applets
  772. JS::NonnullGCPtr<HTMLCollection> Document::applets()
  773. {
  774. // FIXME: This should return the same HTMLCollection object every time,
  775. // but that would cause a reference cycle since HTMLCollection refs the root.
  776. return HTMLCollection::create(*this, [](auto&) { return false; });
  777. }
  778. // https://html.spec.whatwg.org/multipage/obsolete.html#dom-document-anchors
  779. JS::NonnullGCPtr<HTMLCollection> Document::anchors()
  780. {
  781. // FIXME: This should return the same HTMLCollection object every time,
  782. // but that would cause a reference cycle since HTMLCollection refs the root.
  783. return HTMLCollection::create(*this, [](Element const& element) {
  784. return is<HTML::HTMLAnchorElement>(element) && element.has_attribute(HTML::AttributeNames::name);
  785. });
  786. }
  787. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-images
  788. JS::NonnullGCPtr<HTMLCollection> Document::images()
  789. {
  790. // FIXME: This should return the same HTMLCollection object every time,
  791. // but that would cause a reference cycle since HTMLCollection refs the root.
  792. return HTMLCollection::create(*this, [](Element const& element) {
  793. return is<HTML::HTMLImageElement>(element);
  794. });
  795. }
  796. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-embeds
  797. JS::NonnullGCPtr<HTMLCollection> Document::embeds()
  798. {
  799. // FIXME: This should return the same HTMLCollection object every time,
  800. // but that would cause a reference cycle since HTMLCollection refs the root.
  801. return HTMLCollection::create(*this, [](Element const& element) {
  802. return is<HTML::HTMLEmbedElement>(element);
  803. });
  804. }
  805. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-plugins
  806. JS::NonnullGCPtr<HTMLCollection> Document::plugins()
  807. {
  808. return embeds();
  809. }
  810. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-links
  811. JS::NonnullGCPtr<HTMLCollection> Document::links()
  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::HTMLAnchorElement>(element) || is<HTML::HTMLAreaElement>(element)) && element.has_attribute(HTML::AttributeNames::href);
  817. });
  818. }
  819. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-forms
  820. JS::NonnullGCPtr<HTMLCollection> Document::forms()
  821. {
  822. // FIXME: This should return the same HTMLCollection object every time,
  823. // but that would cause a reference cycle since HTMLCollection refs the root.
  824. return HTMLCollection::create(*this, [](Element const& element) {
  825. return is<HTML::HTMLFormElement>(element);
  826. });
  827. }
  828. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-scripts
  829. JS::NonnullGCPtr<HTMLCollection> Document::scripts()
  830. {
  831. // FIXME: This should return the same HTMLCollection object every time,
  832. // but that would cause a reference cycle since HTMLCollection refs the root.
  833. return HTMLCollection::create(*this, [](Element const& element) {
  834. return is<HTML::HTMLScriptElement>(element);
  835. });
  836. }
  837. Color Document::link_color() const
  838. {
  839. if (m_link_color.has_value())
  840. return m_link_color.value();
  841. if (!page())
  842. return Color::Blue;
  843. return page()->palette().link();
  844. }
  845. Color Document::active_link_color() const
  846. {
  847. if (m_active_link_color.has_value())
  848. return m_active_link_color.value();
  849. if (!page())
  850. return Color::Red;
  851. return page()->palette().active_link();
  852. }
  853. Color Document::visited_link_color() const
  854. {
  855. if (m_visited_link_color.has_value())
  856. return m_visited_link_color.value();
  857. if (!page())
  858. return Color::Magenta;
  859. return page()->palette().visited_link();
  860. }
  861. // https://html.spec.whatwg.org/multipage/webappapis.html#relevant-settings-object
  862. HTML::EnvironmentSettingsObject& Document::relevant_settings_object()
  863. {
  864. // Then, the relevant settings object for a platform object o is the environment settings object of the relevant Realm for o.
  865. return verify_cast<HTML::EnvironmentSettingsObject>(*realm().host_defined());
  866. }
  867. JS::Value Document::run_javascript(StringView source, StringView filename)
  868. {
  869. // 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
  870. auto interpreter = JS::Interpreter::create_with_existing_realm(realm());
  871. auto script_or_error = JS::Script::parse(source, realm(), filename);
  872. if (script_or_error.is_error()) {
  873. // FIXME: Add error logging back.
  874. return JS::js_undefined();
  875. }
  876. auto result = interpreter->run(script_or_error.value());
  877. if (result.is_error()) {
  878. // FIXME: I'm sure the spec could tell us something about error propagation here!
  879. HTML::report_exception(result);
  880. return {};
  881. }
  882. return result.value();
  883. }
  884. // https://dom.spec.whatwg.org/#dom-document-createelement
  885. DOM::ExceptionOr<JS::NonnullGCPtr<Element>> Document::create_element(FlyString const& a_local_name)
  886. {
  887. auto local_name = a_local_name;
  888. // 1. If localName does not match the Name production, then throw an "InvalidCharacterError" DOMException.
  889. if (!is_valid_name(local_name))
  890. return DOM::InvalidCharacterError::create(global_object(), "Invalid character in tag name.");
  891. // 2. If this is an HTML document, then set localName to localName in ASCII lowercase.
  892. if (document_type() == Type::HTML)
  893. local_name = local_name.to_lowercase();
  894. // FIXME: 3. Let is be null.
  895. // FIXME: 4. If options is a dictionary and options["is"] exists, then set is to it.
  896. // 5. Let namespace be the HTML namespace, if this is an HTML document or this’s content type is "application/xhtml+xml"; otherwise null.
  897. FlyString namespace_;
  898. if (document_type() == Type::HTML || content_type() == "application/xhtml+xml"sv)
  899. namespace_ = Namespace::HTML;
  900. // 6. Return the result of creating an element given this, localName, namespace, null, is, and with the synchronous custom elements flag set.
  901. return DOM::create_element(*this, local_name, namespace_);
  902. }
  903. // https://dom.spec.whatwg.org/#dom-document-createelementns
  904. // https://dom.spec.whatwg.org/#internal-createelementns-steps
  905. // FIXME: This only implements step 4 of the algorithm and does not take in options.
  906. DOM::ExceptionOr<JS::NonnullGCPtr<Element>> Document::create_element_ns(String const& namespace_, String const& qualified_name)
  907. {
  908. // 1. Let namespace, prefix, and localName be the result of passing namespace and qualifiedName to validate and extract.
  909. auto extracted_qualified_name = TRY(validate_and_extract(global_object(), namespace_, qualified_name));
  910. // FIXME: 2. Let is be null.
  911. // FIXME: 3. If options is a dictionary and options["is"] exists, then set is to it.
  912. // 4. Return the result of creating an element given document, localName, namespace, prefix, is, and with the synchronous custom elements flag set.
  913. return DOM::create_element(*this, extracted_qualified_name.local_name(), extracted_qualified_name.namespace_(), extracted_qualified_name.prefix());
  914. }
  915. JS::NonnullGCPtr<DocumentFragment> Document::create_document_fragment()
  916. {
  917. return *heap().allocate<DocumentFragment>(realm(), *this);
  918. }
  919. JS::NonnullGCPtr<Text> Document::create_text_node(String const& data)
  920. {
  921. return *heap().allocate<Text>(realm(), *this, data);
  922. }
  923. JS::NonnullGCPtr<Comment> Document::create_comment(String const& data)
  924. {
  925. return *heap().allocate<Comment>(realm(), *this, data);
  926. }
  927. JS::NonnullGCPtr<Range> Document::create_range()
  928. {
  929. return Range::create(*this);
  930. }
  931. // https://dom.spec.whatwg.org/#dom-document-createevent
  932. DOM::ExceptionOr<JS::NonnullGCPtr<Event>> Document::create_event(String const& interface)
  933. {
  934. auto& window_object = window();
  935. // NOTE: This is named event here, since we do step 5 and 6 as soon as possible for each case.
  936. // 1. Let constructor be null.
  937. JS::GCPtr<Event> event;
  938. // 2. If interface is an ASCII case-insensitive match for any of the strings in the first column in the following table,
  939. // then set constructor to the interface in the second column on the same row as the matching string:
  940. auto interface_lowercase = interface.to_lowercase();
  941. if (interface_lowercase == "beforeunloadevent") {
  942. event = Event::create(window_object, ""); // FIXME: Create BeforeUnloadEvent
  943. } else if (interface_lowercase == "compositionevent") {
  944. event = Event::create(window_object, ""); // FIXME: Create CompositionEvent
  945. } else if (interface_lowercase == "customevent") {
  946. event = CustomEvent::create(window_object, "");
  947. } else if (interface_lowercase == "devicemotionevent") {
  948. event = Event::create(window_object, ""); // FIXME: Create DeviceMotionEvent
  949. } else if (interface_lowercase == "deviceorientationevent") {
  950. event = Event::create(window_object, ""); // FIXME: Create DeviceOrientationEvent
  951. } else if (interface_lowercase == "dragevent") {
  952. event = Event::create(window_object, ""); // FIXME: Create DragEvent
  953. } else if (interface_lowercase.is_one_of("event", "events")) {
  954. event = Event::create(window_object, "");
  955. } else if (interface_lowercase == "focusevent") {
  956. event = UIEvents::FocusEvent::create(window_object, "");
  957. } else if (interface_lowercase == "hashchangeevent") {
  958. event = Event::create(window_object, ""); // FIXME: Create HashChangeEvent
  959. } else if (interface_lowercase == "htmlevents") {
  960. event = Event::create(window_object, "");
  961. } else if (interface_lowercase == "keyboardevent") {
  962. event = UIEvents::KeyboardEvent::create(window_object, "");
  963. } else if (interface_lowercase == "messageevent") {
  964. event = HTML::MessageEvent::create(window_object, "");
  965. } else if (interface_lowercase.is_one_of("mouseevent", "mouseevents")) {
  966. event = UIEvents::MouseEvent::create(window_object, "");
  967. } else if (interface_lowercase == "storageevent") {
  968. event = Event::create(window_object, ""); // FIXME: Create StorageEvent
  969. } else if (interface_lowercase == "svgevents") {
  970. event = Event::create(window_object, "");
  971. } else if (interface_lowercase == "textevent") {
  972. event = Event::create(window_object, ""); // FIXME: Create CompositionEvent
  973. } else if (interface_lowercase == "touchevent") {
  974. event = Event::create(window_object, ""); // FIXME: Create TouchEvent
  975. } else if (interface_lowercase.is_one_of("uievent", "uievents")) {
  976. event = UIEvents::UIEvent::create(window_object, "");
  977. }
  978. // 3. If constructor is null, then throw a "NotSupportedError" DOMException.
  979. if (!event) {
  980. return DOM::NotSupportedError::create(global_object(), "No constructor for interface found");
  981. }
  982. // FIXME: 4. If the interface indicated by constructor is not exposed on the relevant global object of this, then throw a "NotSupportedError" DOMException.
  983. // NOTE: These are done in the if-chain above
  984. // 5. Let event be the result of creating an event given constructor.
  985. // 6. Initialize event’s type attribute to the empty string.
  986. // NOTE: This is handled by each constructor.
  987. // FIXME: 7. Initialize event’s timeStamp attribute to the result of calling current high resolution time with this’s relevant global object.
  988. // 8. Initialize event’s isTrusted attribute to false.
  989. event->set_is_trusted(false);
  990. // 9. Unset event’s initialized flag.
  991. event->set_initialized(false);
  992. // 10. Return event.
  993. return JS::NonnullGCPtr(*event);
  994. }
  995. void Document::set_pending_parsing_blocking_script(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement* script)
  996. {
  997. m_pending_parsing_blocking_script = script;
  998. }
  999. JS::NonnullGCPtr<HTML::HTMLScriptElement> Document::take_pending_parsing_blocking_script(Badge<HTML::HTMLParser>)
  1000. {
  1001. VERIFY(m_pending_parsing_blocking_script);
  1002. auto script = m_pending_parsing_blocking_script;
  1003. m_pending_parsing_blocking_script = nullptr;
  1004. return *script;
  1005. }
  1006. void Document::add_script_to_execute_when_parsing_has_finished(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement& script)
  1007. {
  1008. m_scripts_to_execute_when_parsing_has_finished.append(JS::make_handle(script));
  1009. }
  1010. Vector<JS::Handle<HTML::HTMLScriptElement>> Document::take_scripts_to_execute_when_parsing_has_finished(Badge<HTML::HTMLParser>)
  1011. {
  1012. return move(m_scripts_to_execute_when_parsing_has_finished);
  1013. }
  1014. void Document::add_script_to_execute_as_soon_as_possible(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement& script)
  1015. {
  1016. m_scripts_to_execute_as_soon_as_possible.append(JS::make_handle(script));
  1017. }
  1018. Vector<JS::Handle<HTML::HTMLScriptElement>> Document::take_scripts_to_execute_as_soon_as_possible(Badge<HTML::HTMLParser>)
  1019. {
  1020. return move(m_scripts_to_execute_as_soon_as_possible);
  1021. }
  1022. // https://dom.spec.whatwg.org/#dom-document-importnode
  1023. ExceptionOr<JS::NonnullGCPtr<Node>> Document::import_node(JS::NonnullGCPtr<Node> node, bool deep)
  1024. {
  1025. // 1. If node is a document or shadow root, then throw a "NotSupportedError" DOMException.
  1026. if (is<Document>(*node) || is<ShadowRoot>(*node))
  1027. return DOM::NotSupportedError::create(global_object(), "Cannot import a document or shadow root.");
  1028. // 2. Return a clone of node, with this and the clone children flag set if deep is true.
  1029. return node->clone_node(this, deep);
  1030. }
  1031. // https://dom.spec.whatwg.org/#concept-node-adopt
  1032. void Document::adopt_node(Node& node)
  1033. {
  1034. auto& old_document = node.document();
  1035. if (node.parent())
  1036. node.remove();
  1037. if (&old_document != this) {
  1038. node.for_each_shadow_including_descendant([&](auto& inclusive_descendant) {
  1039. inclusive_descendant.set_document({}, *this);
  1040. // FIXME: If inclusiveDescendant is an element, then set the node document of each attribute in inclusiveDescendant’s attribute list to document.
  1041. return IterationDecision::Continue;
  1042. });
  1043. // FIXME: For each inclusiveDescendant in node’s shadow-including inclusive descendants that is custom,
  1044. // enqueue a custom element callback reaction with inclusiveDescendant, callback name "adoptedCallback",
  1045. // and an argument list containing oldDocument and document.
  1046. node.for_each_shadow_including_descendant([&](auto& inclusive_descendant) {
  1047. inclusive_descendant.adopted_from(old_document);
  1048. return IterationDecision::Continue;
  1049. });
  1050. // Transfer NodeIterators rooted at `node` from old_document to this document.
  1051. Vector<NodeIterator&> node_iterators_to_transfer;
  1052. for (auto node_iterator : old_document.m_node_iterators) {
  1053. if (node_iterator->root().ptr() == &node)
  1054. node_iterators_to_transfer.append(*node_iterator);
  1055. }
  1056. for (auto& node_iterator : node_iterators_to_transfer) {
  1057. old_document.m_node_iterators.remove(&node_iterator);
  1058. m_node_iterators.set(&node_iterator);
  1059. }
  1060. }
  1061. }
  1062. // https://dom.spec.whatwg.org/#dom-document-adoptnode
  1063. ExceptionOr<JS::NonnullGCPtr<Node>> Document::adopt_node_binding(JS::NonnullGCPtr<Node> node)
  1064. {
  1065. if (is<Document>(*node))
  1066. return DOM::NotSupportedError::create(global_object(), "Cannot adopt a document into a document");
  1067. if (is<ShadowRoot>(*node))
  1068. return DOM::HierarchyRequestError::create(global_object(), "Cannot adopt a shadow root into a document");
  1069. if (is<DocumentFragment>(*node) && verify_cast<DocumentFragment>(*node).host())
  1070. return node;
  1071. adopt_node(*node);
  1072. return node;
  1073. }
  1074. DocumentType const* Document::doctype() const
  1075. {
  1076. return first_child_of_type<DocumentType>();
  1077. }
  1078. String const& Document::compat_mode() const
  1079. {
  1080. static String back_compat = "BackCompat";
  1081. static String css1_compat = "CSS1Compat";
  1082. if (m_quirks_mode == QuirksMode::Yes)
  1083. return back_compat;
  1084. return css1_compat;
  1085. }
  1086. bool Document::is_editable() const
  1087. {
  1088. return m_editable;
  1089. }
  1090. void Document::set_focused_element(Element* element)
  1091. {
  1092. if (m_focused_element.ptr() == element)
  1093. return;
  1094. if (m_focused_element) {
  1095. m_focused_element->did_lose_focus();
  1096. m_focused_element->set_needs_style_update(true);
  1097. }
  1098. m_focused_element = element;
  1099. if (m_focused_element) {
  1100. m_focused_element->did_receive_focus();
  1101. m_focused_element->set_needs_style_update(true);
  1102. }
  1103. if (m_layout_root)
  1104. m_layout_root->set_needs_display();
  1105. }
  1106. void Document::set_active_element(Element* element)
  1107. {
  1108. if (m_active_element.ptr() == element)
  1109. return;
  1110. m_active_element = element;
  1111. if (m_layout_root)
  1112. m_layout_root->set_needs_display();
  1113. }
  1114. String Document::ready_state() const
  1115. {
  1116. switch (m_readiness) {
  1117. case HTML::DocumentReadyState::Loading:
  1118. return "loading"sv;
  1119. case HTML::DocumentReadyState::Interactive:
  1120. return "interactive"sv;
  1121. case HTML::DocumentReadyState::Complete:
  1122. return "complete"sv;
  1123. }
  1124. VERIFY_NOT_REACHED();
  1125. }
  1126. // https://html.spec.whatwg.org/#update-the-current-document-readiness
  1127. void Document::update_readiness(HTML::DocumentReadyState readiness_value)
  1128. {
  1129. // 1. If document's current document readiness equals readinessValue, then return.
  1130. if (m_readiness == readiness_value)
  1131. return;
  1132. // The spec doesn't actually mention updating the current readiness value.
  1133. // FIXME: https://github.com/whatwg/html/issues/7120
  1134. m_readiness = readiness_value;
  1135. // FIXME: 2. If document is associated with an HTML parser, then:
  1136. // FIXME: 1. If document is associated with an HTML parser, then:
  1137. // 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.
  1138. // 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.
  1139. // 3. Fire an event named readystatechange at document.
  1140. dispatch_event(*Event::create(window(), HTML::EventNames::readystatechange));
  1141. }
  1142. Page* Document::page()
  1143. {
  1144. return m_browsing_context ? m_browsing_context->page() : nullptr;
  1145. }
  1146. Page const* Document::page() const
  1147. {
  1148. return m_browsing_context ? m_browsing_context->page() : nullptr;
  1149. }
  1150. EventTarget* Document::get_parent(Event const& event)
  1151. {
  1152. if (event.type() == HTML::EventNames::load)
  1153. return nullptr;
  1154. return &window();
  1155. }
  1156. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#completely-finish-loading
  1157. void Document::completely_finish_loading()
  1158. {
  1159. // 1. Assert: document's browsing context is non-null.
  1160. VERIFY(browsing_context());
  1161. // FIXME: 2. Set document's completely loaded time to the current time.
  1162. // 3. Let container be document's browsing context's container.
  1163. auto container = JS::make_handle(browsing_context()->container());
  1164. // 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.
  1165. if (container && is<HTML::HTMLIFrameElement>(*container)) {
  1166. container->queue_an_element_task(HTML::Task::Source::DOMManipulation, [container]() mutable {
  1167. run_iframe_load_event_steps(static_cast<HTML::HTMLIFrameElement&>(*container));
  1168. });
  1169. }
  1170. // 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.
  1171. else if (container) {
  1172. container->queue_an_element_task(HTML::Task::Source::DOMManipulation, [container]() mutable {
  1173. container->dispatch_event(*DOM::Event::create(container->window(), HTML::EventNames::load));
  1174. });
  1175. }
  1176. }
  1177. String Document::cookie(Cookie::Source source)
  1178. {
  1179. if (auto* page = this->page())
  1180. return page->client().page_did_request_cookie(m_url, source);
  1181. return {};
  1182. }
  1183. void Document::set_cookie(String const& cookie_string, Cookie::Source source)
  1184. {
  1185. auto cookie = Cookie::parse_cookie(cookie_string);
  1186. if (!cookie.has_value())
  1187. return;
  1188. if (auto* page = this->page())
  1189. page->client().page_did_set_cookie(m_url, cookie.value(), source);
  1190. }
  1191. String Document::dump_dom_tree_as_json() const
  1192. {
  1193. StringBuilder builder;
  1194. auto json = MUST(JsonObjectSerializer<>::try_create(builder));
  1195. serialize_tree_as_json(json);
  1196. MUST(json.finish());
  1197. return builder.to_string();
  1198. }
  1199. // https://html.spec.whatwg.org/multipage/semantics.html#has-a-style-sheet-that-is-blocking-scripts
  1200. bool Document::has_a_style_sheet_that_is_blocking_scripts() const
  1201. {
  1202. // A Document has a style sheet that is blocking scripts if its script-blocking style sheet counter is greater than 0,
  1203. if (m_script_blocking_style_sheet_counter > 0)
  1204. return true;
  1205. // ...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.
  1206. if (!browsing_context() || !browsing_context()->container_document())
  1207. return false;
  1208. return browsing_context()->container_document()->m_script_blocking_style_sheet_counter > 0;
  1209. }
  1210. String Document::referrer() const
  1211. {
  1212. return m_referrer;
  1213. }
  1214. void Document::set_referrer(String referrer)
  1215. {
  1216. m_referrer = referrer;
  1217. }
  1218. // https://html.spec.whatwg.org/multipage/browsers.html#fully-active
  1219. bool Document::is_fully_active() const
  1220. {
  1221. // 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,
  1222. // and either d's browsing context is a top-level browsing context, or d's browsing context's container document is fully active.
  1223. auto* browsing_context = this->browsing_context();
  1224. if (!browsing_context)
  1225. return false;
  1226. if (browsing_context->active_document() != this)
  1227. return false;
  1228. if (browsing_context->is_top_level())
  1229. return true;
  1230. if (auto* browsing_context_container_document = browsing_context->container_document()) {
  1231. if (browsing_context_container_document->is_fully_active())
  1232. return true;
  1233. }
  1234. return false;
  1235. }
  1236. // https://html.spec.whatwg.org/multipage/browsers.html#active-document
  1237. bool Document::is_active() const
  1238. {
  1239. // A browsing context's active document is its active window's associated Document.
  1240. return browsing_context() && browsing_context()->active_document() == this;
  1241. }
  1242. // https://html.spec.whatwg.org/multipage/history.html#dom-document-location
  1243. Bindings::LocationObject* Document::location()
  1244. {
  1245. // The Document object's location attribute's getter must return this Document object's relevant global object's Location object,
  1246. // if this Document object is fully active, and null otherwise.
  1247. if (!is_fully_active())
  1248. return nullptr;
  1249. return window().location_object();
  1250. }
  1251. // https://html.spec.whatwg.org/multipage/interaction.html#dom-document-hidden
  1252. bool Document::hidden() const
  1253. {
  1254. return false;
  1255. }
  1256. // https://html.spec.whatwg.org/multipage/interaction.html#dom-document-visibilitystate
  1257. String Document::visibility_state() const
  1258. {
  1259. return hidden() ? "hidden" : "visible";
  1260. }
  1261. // https://drafts.csswg.org/cssom-view/#run-the-resize-steps
  1262. void Document::run_the_resize_steps()
  1263. {
  1264. // 1. If doc’s viewport has had its width or height changed
  1265. // (e.g. as a result of the user resizing the browser window, or changing the page zoom scale factor,
  1266. // or an iframe element’s dimensions are changed) since the last time these steps were run,
  1267. // fire an event named resize at the Window object associated with doc.
  1268. if (!browsing_context())
  1269. return;
  1270. auto viewport_size = browsing_context()->viewport_rect().size();
  1271. if (m_last_viewport_size == viewport_size)
  1272. return;
  1273. m_last_viewport_size = viewport_size;
  1274. window().dispatch_event(*DOM::Event::create(window(), UIEvents::EventNames::resize));
  1275. update_layout();
  1276. }
  1277. void Document::add_media_query_list(JS::NonnullGCPtr<CSS::MediaQueryList> media_query_list)
  1278. {
  1279. m_media_query_lists.append(*media_query_list);
  1280. }
  1281. // https://drafts.csswg.org/cssom-view/#evaluate-media-queries-and-report-changes
  1282. void Document::evaluate_media_queries_and_report_changes()
  1283. {
  1284. // NOTE: Not in the spec, but we take this opportunity to prune null WeakPtrs.
  1285. m_media_query_lists.remove_all_matching([](auto& it) {
  1286. return it.is_null();
  1287. });
  1288. // 1. For each MediaQueryList object target that has doc as its document,
  1289. // in the order they were created, oldest first, run these substeps:
  1290. for (auto& media_query_list_ptr : m_media_query_lists) {
  1291. // 1. If target’s matches state has changed since the last time these steps
  1292. // were run, fire an event at target using the MediaQueryListEvent constructor,
  1293. // with its type attribute initialized to change, its isTrusted attribute
  1294. // initialized to true, its media attribute initialized to target’s media,
  1295. // and its matches attribute initialized to target’s matches state.
  1296. if (media_query_list_ptr.is_null())
  1297. continue;
  1298. JS::GCPtr<CSS::MediaQueryList> media_query_list = media_query_list_ptr.ptr();
  1299. bool did_match = media_query_list->matches();
  1300. bool now_matches = media_query_list->evaluate();
  1301. if (did_match != now_matches) {
  1302. CSS::MediaQueryListEventInit init;
  1303. init.media = media_query_list->media();
  1304. init.matches = now_matches;
  1305. auto event = CSS::MediaQueryListEvent::create(window(), HTML::EventNames::change, init);
  1306. event->set_is_trusted(true);
  1307. media_query_list->dispatch_event(*event);
  1308. }
  1309. }
  1310. // Also not in the spec, but this is as good a place as any to evaluate @media rules!
  1311. evaluate_media_rules();
  1312. }
  1313. void Document::evaluate_media_rules()
  1314. {
  1315. bool any_media_queries_changed_match_state = false;
  1316. for (auto& style_sheet : style_sheets().sheets()) {
  1317. if (style_sheet->evaluate_media_queries(window()))
  1318. any_media_queries_changed_match_state = true;
  1319. }
  1320. if (any_media_queries_changed_match_state) {
  1321. style_computer().invalidate_rule_cache();
  1322. invalidate_style();
  1323. }
  1324. }
  1325. DOMImplementation* Document::implementation()
  1326. {
  1327. if (!m_implementation)
  1328. m_implementation = DOMImplementation::create(*this);
  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(JS::Object& global_object, String const& qualified_name)
  1389. {
  1390. if (qualified_name.is_empty())
  1391. return InvalidCharacterError::create(global_object, "Empty string is not a valid qualified name.");
  1392. Utf8View utf8view { qualified_name };
  1393. if (!utf8view.validate())
  1394. return InvalidCharacterError::create(global_object, "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(global_object, "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(global_object, "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(global_object, "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(global_object, "Qualified name can't start with colon (:).");
  1422. if (*colon_offset >= (qualified_name.length() - 1))
  1423. return InvalidCharacterError::create(global_object, "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. JS::NonnullGCPtr<NodeIterator> Document::create_node_iterator(Node& root, unsigned what_to_show, JS::GCPtr<NodeFilter> filter)
  1431. {
  1432. return NodeIterator::create(root, what_to_show, filter);
  1433. }
  1434. // https://dom.spec.whatwg.org/#dom-document-createtreewalker
  1435. JS::NonnullGCPtr<TreeWalker> Document::create_tree_walker(Node& root, unsigned what_to_show, JS::GCPtr<NodeFilter> filter)
  1436. {
  1437. return TreeWalker::create(root, what_to_show, 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.ptr())
  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. CSS::StyleSheetList& Document::style_sheets()
  1509. {
  1510. if (!m_style_sheets)
  1511. m_style_sheets = CSS::StyleSheetList::create(*this);
  1512. return *m_style_sheets;
  1513. }
  1514. CSS::StyleSheetList const& Document::style_sheets() const
  1515. {
  1516. return const_cast<Document*>(this)->style_sheets();
  1517. }
  1518. JS::NonnullGCPtr<HTML::History> Document::history()
  1519. {
  1520. if (!m_history)
  1521. m_history = HTML::History::create(window(), *this);
  1522. return *m_history;
  1523. }
  1524. // https://html.spec.whatwg.org/multipage/origin.html#dom-document-domain
  1525. String Document::domain() const
  1526. {
  1527. // 1. Let effectiveDomain be this's origin's effective domain.
  1528. auto effective_domain = origin().effective_domain();
  1529. // 2. If effectiveDomain is null, then return the empty string.
  1530. if (!effective_domain.has_value())
  1531. return String::empty();
  1532. // 3. Return effectiveDomain, serialized.
  1533. // FIXME: Implement host serialization.
  1534. return effective_domain.release_value();
  1535. }
  1536. void Document::set_domain(String const& domain)
  1537. {
  1538. dbgln("(STUBBED) Document::set_domain(domain='{}')", domain);
  1539. }
  1540. }