Document.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, 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/Range.h>
  34. #include <LibWeb/DOM/ShadowRoot.h>
  35. #include <LibWeb/DOM/Text.h>
  36. #include <LibWeb/DOM/Window.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/HTMLBodyElement.h>
  45. #include <LibWeb/HTML/HTMLEmbedElement.h>
  46. #include <LibWeb/HTML/HTMLFormElement.h>
  47. #include <LibWeb/HTML/HTMLFrameSetElement.h>
  48. #include <LibWeb/HTML/HTMLHeadElement.h>
  49. #include <LibWeb/HTML/HTMLHtmlElement.h>
  50. #include <LibWeb/HTML/HTMLIFrameElement.h>
  51. #include <LibWeb/HTML/HTMLImageElement.h>
  52. #include <LibWeb/HTML/HTMLScriptElement.h>
  53. #include <LibWeb/HTML/HTMLTitleElement.h>
  54. #include <LibWeb/HTML/MessageEvent.h>
  55. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  56. #include <LibWeb/Layout/BlockFormattingContext.h>
  57. #include <LibWeb/Layout/InitialContainingBlock.h>
  58. #include <LibWeb/Layout/TreeBuilder.h>
  59. #include <LibWeb/Namespace.h>
  60. #include <LibWeb/Origin.h>
  61. #include <LibWeb/Page/Page.h>
  62. #include <LibWeb/SVG/TagNames.h>
  63. #include <LibWeb/UIEvents/EventNames.h>
  64. #include <LibWeb/UIEvents/FocusEvent.h>
  65. #include <LibWeb/UIEvents/KeyboardEvent.h>
  66. #include <LibWeb/UIEvents/MouseEvent.h>
  67. namespace Web::DOM {
  68. Document::Document(const AK::URL& url)
  69. : ParentNode(*this, NodeType::DOCUMENT_NODE)
  70. , m_style_computer(make<CSS::StyleComputer>(*this))
  71. , m_style_sheets(CSS::StyleSheetList::create(*this))
  72. , m_url(url)
  73. , m_window(Window::create_with_document(*this))
  74. , m_implementation(DOMImplementation::create({}, *this))
  75. , m_history(HTML::History::create(*this))
  76. {
  77. HTML::main_thread_event_loop().register_document({}, *this);
  78. m_style_update_timer = Core::Timer::create_single_shot(0, [this] {
  79. update_style();
  80. });
  81. m_layout_update_timer = Core::Timer::create_single_shot(0, [this] {
  82. force_layout();
  83. });
  84. }
  85. Document::~Document()
  86. {
  87. }
  88. void Document::removed_last_ref()
  89. {
  90. VERIFY(!ref_count());
  91. VERIFY(!m_deletion_has_begun);
  92. if (m_referencing_node_count) {
  93. // The document has reached ref_count==0 but still has nodes keeping it alive.
  94. // At this point, sever all the node links we control.
  95. // If nodes remain elsewhere (e.g JS wrappers), they will keep the document alive.
  96. // NOTE: This makes sure we stay alive across for the duration of the cleanup below.
  97. increment_referencing_node_count();
  98. m_focused_element = nullptr;
  99. m_hovered_node = nullptr;
  100. m_pending_parsing_blocking_script = nullptr;
  101. m_inspected_node = nullptr;
  102. m_scripts_to_execute_when_parsing_has_finished.clear();
  103. m_scripts_to_execute_as_soon_as_possible.clear();
  104. m_associated_inert_template_document = nullptr;
  105. m_interpreter = nullptr;
  106. {
  107. // Gather up all the descendants of this document and prune them from the tree.
  108. // FIXME: This could definitely be more elegant.
  109. NonnullRefPtrVector<Node> descendants;
  110. for_each_in_inclusive_subtree([&](auto& node) {
  111. if (&node != this)
  112. descendants.append(node);
  113. return IterationDecision::Continue;
  114. });
  115. for (auto& node : descendants) {
  116. VERIFY(&node.document() == this);
  117. VERIFY(!node.is_document());
  118. if (node.parent())
  119. node.remove();
  120. }
  121. }
  122. m_in_removed_last_ref = false;
  123. decrement_referencing_node_count();
  124. return;
  125. }
  126. m_in_removed_last_ref = false;
  127. m_deletion_has_begun = true;
  128. HTML::main_thread_event_loop().unregister_document({}, *this);
  129. delete this;
  130. }
  131. Origin Document::origin() const
  132. {
  133. if (!m_url.is_valid())
  134. return {};
  135. return { m_url.protocol(), m_url.host(), m_url.port_or_default() };
  136. }
  137. void Document::set_origin(const Origin& origin)
  138. {
  139. m_url.set_protocol(origin.protocol());
  140. m_url.set_host(origin.host());
  141. m_url.set_port(origin.port());
  142. }
  143. void Document::schedule_style_update()
  144. {
  145. if (m_style_update_timer->is_active())
  146. return;
  147. m_style_update_timer->start();
  148. }
  149. void Document::schedule_layout_update()
  150. {
  151. if (m_layout_update_timer->is_active())
  152. return;
  153. m_layout_update_timer->start();
  154. }
  155. bool Document::is_child_allowed(const Node& node) const
  156. {
  157. switch (node.type()) {
  158. case NodeType::DOCUMENT_NODE:
  159. case NodeType::TEXT_NODE:
  160. return false;
  161. case NodeType::COMMENT_NODE:
  162. return true;
  163. case NodeType::DOCUMENT_TYPE_NODE:
  164. return !first_child_of_type<DocumentType>();
  165. case NodeType::ELEMENT_NODE:
  166. return !first_child_of_type<Element>();
  167. default:
  168. return false;
  169. }
  170. }
  171. Element* Document::document_element()
  172. {
  173. return first_child_of_type<Element>();
  174. }
  175. const Element* Document::document_element() const
  176. {
  177. return first_child_of_type<Element>();
  178. }
  179. HTML::HTMLHtmlElement* Document::html_element()
  180. {
  181. auto* html = document_element();
  182. if (is<HTML::HTMLHtmlElement>(html))
  183. return verify_cast<HTML::HTMLHtmlElement>(html);
  184. return nullptr;
  185. }
  186. HTML::HTMLHeadElement* Document::head()
  187. {
  188. auto* html = html_element();
  189. if (!html)
  190. return nullptr;
  191. return html->first_child_of_type<HTML::HTMLHeadElement>();
  192. }
  193. HTML::HTMLElement* Document::body()
  194. {
  195. auto* html = html_element();
  196. if (!html)
  197. return nullptr;
  198. auto* first_body = html->first_child_of_type<HTML::HTMLBodyElement>();
  199. if (first_body)
  200. return first_body;
  201. auto* first_frameset = html->first_child_of_type<HTML::HTMLFrameSetElement>();
  202. if (first_frameset)
  203. return first_frameset;
  204. return nullptr;
  205. }
  206. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-body
  207. ExceptionOr<void> Document::set_body(HTML::HTMLElement* new_body)
  208. {
  209. if (!is<HTML::HTMLBodyElement>(new_body) && !is<HTML::HTMLFrameSetElement>(new_body))
  210. return DOM::HierarchyRequestError::create("Invalid document body element, must be 'body' or 'frameset'");
  211. auto* existing_body = body();
  212. if (existing_body) {
  213. auto replace_result = existing_body->parent()->replace_child(*new_body, *existing_body);
  214. if (replace_result.is_exception())
  215. return replace_result.exception();
  216. return {};
  217. }
  218. auto* document_element = this->document_element();
  219. if (!document_element)
  220. return DOM::HierarchyRequestError::create("Missing document element");
  221. auto append_result = document_element->append_child(*new_body);
  222. if (append_result.is_exception())
  223. return append_result.exception();
  224. return {};
  225. }
  226. String Document::title() const
  227. {
  228. auto* head_element = head();
  229. if (!head_element)
  230. return {};
  231. auto* title_element = head_element->first_child_of_type<HTML::HTMLTitleElement>();
  232. if (!title_element)
  233. return {};
  234. auto raw_title = title_element->text_content();
  235. StringBuilder builder;
  236. bool last_was_space = false;
  237. for (auto code_point : Utf8View(raw_title)) {
  238. if (is_ascii_space(code_point)) {
  239. last_was_space = true;
  240. } else {
  241. if (last_was_space && !builder.is_empty())
  242. builder.append(' ');
  243. builder.append_code_point(code_point);
  244. last_was_space = false;
  245. }
  246. }
  247. return builder.to_string();
  248. }
  249. void Document::set_title(const String& title)
  250. {
  251. auto* head_element = const_cast<HTML::HTMLHeadElement*>(head());
  252. if (!head_element)
  253. return;
  254. RefPtr<HTML::HTMLTitleElement> title_element = head_element->first_child_of_type<HTML::HTMLTitleElement>();
  255. if (!title_element) {
  256. title_element = static_ptr_cast<HTML::HTMLTitleElement>(create_element(HTML::TagNames::title));
  257. head_element->append_child(*title_element);
  258. }
  259. title_element->remove_all_children(true);
  260. title_element->append_child(adopt_ref(*new Text(*this, title)));
  261. if (auto* page = this->page()) {
  262. if (browsing_context() == &page->top_level_browsing_context())
  263. page->client().page_did_change_title(title);
  264. }
  265. }
  266. void Document::attach_to_browsing_context(Badge<HTML::BrowsingContext>, HTML::BrowsingContext& browsing_context)
  267. {
  268. m_browsing_context = browsing_context;
  269. update_layout();
  270. }
  271. void Document::detach_from_browsing_context(Badge<HTML::BrowsingContext>, HTML::BrowsingContext& browsing_context)
  272. {
  273. VERIFY(&browsing_context == m_browsing_context);
  274. tear_down_layout_tree();
  275. m_browsing_context = nullptr;
  276. }
  277. void Document::tear_down_layout_tree()
  278. {
  279. if (!m_layout_root)
  280. return;
  281. // Gather up all the layout nodes in a vector and detach them from parents
  282. // while the vector keeps them alive.
  283. NonnullRefPtrVector<Layout::Node> layout_nodes;
  284. m_layout_root->for_each_in_inclusive_subtree([&](auto& layout_node) {
  285. layout_nodes.append(layout_node);
  286. return IterationDecision::Continue;
  287. });
  288. for (auto& layout_node : layout_nodes) {
  289. if (layout_node.parent())
  290. layout_node.parent()->remove_child(layout_node);
  291. }
  292. m_layout_root = nullptr;
  293. }
  294. Color Document::background_color(const Palette& palette) const
  295. {
  296. auto default_color = palette.base();
  297. auto* body_element = body();
  298. if (!body_element)
  299. return default_color;
  300. auto* body_layout_node = body_element->layout_node();
  301. if (!body_layout_node)
  302. return default_color;
  303. auto color = body_layout_node->computed_values().background_color();
  304. if (!color.alpha())
  305. return default_color;
  306. return color;
  307. }
  308. Vector<CSS::BackgroundLayerData> const* Document::background_layers() const
  309. {
  310. auto* body_element = body();
  311. if (!body_element)
  312. return {};
  313. auto* body_layout_node = body_element->layout_node();
  314. if (!body_layout_node)
  315. return {};
  316. return &body_layout_node->background_layers();
  317. }
  318. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#parse-a-url
  319. AK::URL Document::parse_url(String const& url) const
  320. {
  321. // FIXME: Make sure we do this according to spec.
  322. return m_url.complete_url(url);
  323. }
  324. void Document::set_needs_layout()
  325. {
  326. if (m_needs_layout)
  327. return;
  328. m_needs_layout = true;
  329. schedule_layout_update();
  330. }
  331. void Document::force_layout()
  332. {
  333. tear_down_layout_tree();
  334. update_layout();
  335. }
  336. void Document::ensure_layout()
  337. {
  338. if (m_needs_layout || !m_layout_root)
  339. update_layout();
  340. }
  341. void Document::update_layout()
  342. {
  343. if (!m_needs_layout && m_layout_root)
  344. return;
  345. if (!browsing_context())
  346. return;
  347. update_style();
  348. if (!m_layout_root) {
  349. Layout::TreeBuilder tree_builder;
  350. m_layout_root = static_ptr_cast<Layout::InitialContainingBlock>(tree_builder.build(*this));
  351. }
  352. Layout::BlockFormattingContext root_formatting_context(*m_layout_root, nullptr);
  353. root_formatting_context.run(*m_layout_root, Layout::LayoutMode::Default);
  354. m_layout_root->set_needs_display();
  355. if (browsing_context()->is_top_level()) {
  356. if (auto* page = this->page())
  357. page->client().page_did_layout();
  358. }
  359. m_needs_layout = false;
  360. m_layout_update_timer->stop();
  361. }
  362. static void update_style_recursively(DOM::Node& node)
  363. {
  364. if (is<Element>(node))
  365. static_cast<Element&>(node).recompute_style();
  366. node.set_needs_style_update(false);
  367. if (node.child_needs_style_update()) {
  368. node.for_each_child([&](auto& child) {
  369. if (child.needs_style_update() || child.child_needs_style_update())
  370. update_style_recursively(child);
  371. return IterationDecision::Continue;
  372. });
  373. }
  374. node.set_child_needs_style_update(false);
  375. }
  376. void Document::update_style()
  377. {
  378. if (!browsing_context())
  379. return;
  380. if (!needs_style_update() && !child_needs_style_update())
  381. return;
  382. update_style_recursively(*this);
  383. m_style_update_timer->stop();
  384. set_needs_layout();
  385. }
  386. void Document::set_link_color(Color color)
  387. {
  388. m_link_color = color;
  389. }
  390. void Document::set_active_link_color(Color color)
  391. {
  392. m_active_link_color = color;
  393. }
  394. void Document::set_visited_link_color(Color color)
  395. {
  396. m_visited_link_color = color;
  397. }
  398. const Layout::InitialContainingBlock* Document::layout_node() const
  399. {
  400. return static_cast<const Layout::InitialContainingBlock*>(Node::layout_node());
  401. }
  402. Layout::InitialContainingBlock* Document::layout_node()
  403. {
  404. return static_cast<Layout::InitialContainingBlock*>(Node::layout_node());
  405. }
  406. void Document::set_inspected_node(Node* node)
  407. {
  408. if (m_inspected_node == node)
  409. return;
  410. if (m_inspected_node && m_inspected_node->layout_node())
  411. m_inspected_node->layout_node()->set_needs_display();
  412. m_inspected_node = node;
  413. if (m_inspected_node && m_inspected_node->layout_node())
  414. m_inspected_node->layout_node()->set_needs_display();
  415. }
  416. void Document::set_hovered_node(Node* node)
  417. {
  418. if (m_hovered_node == node)
  419. return;
  420. RefPtr<Node> old_hovered_node = move(m_hovered_node);
  421. m_hovered_node = node;
  422. invalidate_style();
  423. }
  424. NonnullRefPtr<HTMLCollection> Document::get_elements_by_name(String const& name)
  425. {
  426. return HTMLCollection::create(*this, [name](Element const& element) {
  427. return element.name() == name;
  428. });
  429. }
  430. NonnullRefPtr<HTMLCollection> Document::get_elements_by_class_name(FlyString const& class_name)
  431. {
  432. return HTMLCollection::create(*this, [class_name, quirks_mode = document().in_quirks_mode()](Element const& element) {
  433. return element.has_class(class_name, quirks_mode ? CaseSensitivity::CaseInsensitive : CaseSensitivity::CaseSensitive);
  434. });
  435. }
  436. // https://html.spec.whatwg.org/multipage/obsolete.html#dom-document-applets
  437. NonnullRefPtr<HTMLCollection> Document::applets()
  438. {
  439. // FIXME: This should return the same HTMLCollection object every time,
  440. // but that would cause a reference cycle since HTMLCollection refs the root.
  441. return HTMLCollection::create(*this, [](auto&) { return false; });
  442. }
  443. // https://html.spec.whatwg.org/multipage/obsolete.html#dom-document-anchors
  444. NonnullRefPtr<HTMLCollection> Document::anchors()
  445. {
  446. // FIXME: This should return the same HTMLCollection object every time,
  447. // but that would cause a reference cycle since HTMLCollection refs the root.
  448. return HTMLCollection::create(*this, [](Element const& element) {
  449. return is<HTML::HTMLAnchorElement>(element) && element.has_attribute(HTML::AttributeNames::name);
  450. });
  451. }
  452. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-images
  453. NonnullRefPtr<HTMLCollection> Document::images()
  454. {
  455. // FIXME: This should return the same HTMLCollection object every time,
  456. // but that would cause a reference cycle since HTMLCollection refs the root.
  457. return HTMLCollection::create(*this, [](Element const& element) {
  458. return is<HTML::HTMLImageElement>(element);
  459. });
  460. }
  461. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-embeds
  462. NonnullRefPtr<HTMLCollection> Document::embeds()
  463. {
  464. // FIXME: This should return the same HTMLCollection object every time,
  465. // but that would cause a reference cycle since HTMLCollection refs the root.
  466. return HTMLCollection::create(*this, [](Element const& element) {
  467. return is<HTML::HTMLEmbedElement>(element);
  468. });
  469. }
  470. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-plugins
  471. NonnullRefPtr<HTMLCollection> Document::plugins()
  472. {
  473. return embeds();
  474. }
  475. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-links
  476. NonnullRefPtr<HTMLCollection> Document::links()
  477. {
  478. // FIXME: This should return the same HTMLCollection object every time,
  479. // but that would cause a reference cycle since HTMLCollection refs the root.
  480. return HTMLCollection::create(*this, [](Element const& element) {
  481. return (is<HTML::HTMLAnchorElement>(element) || is<HTML::HTMLAreaElement>(element)) && element.has_attribute(HTML::AttributeNames::href);
  482. });
  483. }
  484. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-forms
  485. NonnullRefPtr<HTMLCollection> Document::forms()
  486. {
  487. // FIXME: This should return the same HTMLCollection object every time,
  488. // but that would cause a reference cycle since HTMLCollection refs the root.
  489. return HTMLCollection::create(*this, [](Element const& element) {
  490. return is<HTML::HTMLFormElement>(element);
  491. });
  492. }
  493. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-scripts
  494. NonnullRefPtr<HTMLCollection> Document::scripts()
  495. {
  496. // FIXME: This should return the same HTMLCollection object every time,
  497. // but that would cause a reference cycle since HTMLCollection refs the root.
  498. return HTMLCollection::create(*this, [](Element const& element) {
  499. return is<HTML::HTMLScriptElement>(element);
  500. });
  501. }
  502. Color Document::link_color() const
  503. {
  504. if (m_link_color.has_value())
  505. return m_link_color.value();
  506. if (!page())
  507. return Color::Blue;
  508. return page()->palette().link();
  509. }
  510. Color Document::active_link_color() const
  511. {
  512. if (m_active_link_color.has_value())
  513. return m_active_link_color.value();
  514. if (!page())
  515. return Color::Red;
  516. return page()->palette().active_link();
  517. }
  518. Color Document::visited_link_color() const
  519. {
  520. if (m_visited_link_color.has_value())
  521. return m_visited_link_color.value();
  522. if (!page())
  523. return Color::Magenta;
  524. return page()->palette().visited_link();
  525. }
  526. JS::Realm& Document::realm()
  527. {
  528. return interpreter().realm();
  529. }
  530. JS::Interpreter& Document::interpreter()
  531. {
  532. if (!m_interpreter) {
  533. auto& vm = Bindings::main_thread_vm();
  534. m_interpreter = JS::Interpreter::create<Bindings::WindowObject>(vm, *m_window);
  535. // NOTE: We must hook `on_call_stack_emptied` after the interpreter was created, as the initialization of the
  536. // WindowsObject can invoke some internal calls, which will eventually lead to this hook being called without
  537. // `m_interpreter` being fully initialized yet.
  538. // TODO: Hook up vm.on_promise_unhandled_rejection and vm.on_promise_rejection_handled
  539. // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#promise_rejection_events
  540. vm.on_call_stack_emptied = [this] {
  541. auto& vm = m_interpreter->vm();
  542. vm.run_queued_promise_jobs();
  543. vm.run_queued_finalization_registry_cleanup_jobs();
  544. // FIXME: This isn't exactly the right place for this.
  545. HTML::main_thread_event_loop().perform_a_microtask_checkpoint();
  546. vm.finish_execution_generation();
  547. };
  548. }
  549. return *m_interpreter;
  550. }
  551. JS::Value Document::run_javascript(StringView source, StringView filename)
  552. {
  553. // 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
  554. auto& interpreter = document().interpreter();
  555. auto script_or_error = JS::Script::parse(source, interpreter.realm(), filename);
  556. if (script_or_error.is_error()) {
  557. // FIXME: Add error logging back.
  558. return JS::js_undefined();
  559. }
  560. auto result = interpreter.run(script_or_error.value());
  561. if (result.is_error()) {
  562. // FIXME: I'm sure the spec could tell us something about error propagation here!
  563. HTML::report_exception(result);
  564. return {};
  565. }
  566. return result.value();
  567. }
  568. // https://dom.spec.whatwg.org/#dom-document-createelement
  569. // FIXME: This only implements step 6 of the algorithm and does not take in options.
  570. NonnullRefPtr<Element> Document::create_element(const String& tag_name)
  571. {
  572. // 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.
  573. return DOM::create_element(*this, tag_name, Namespace::HTML);
  574. }
  575. // https://dom.spec.whatwg.org/#internal-createelementns-steps
  576. // FIXME: This only implements step 4 of the algorithm and does not take in options.
  577. NonnullRefPtr<Element> Document::create_element_ns(const String& namespace_, const String& qualified_name)
  578. {
  579. return DOM::create_element(*this, qualified_name, namespace_);
  580. }
  581. NonnullRefPtr<DocumentFragment> Document::create_document_fragment()
  582. {
  583. return adopt_ref(*new DocumentFragment(*this));
  584. }
  585. NonnullRefPtr<Text> Document::create_text_node(const String& data)
  586. {
  587. return adopt_ref(*new Text(*this, data));
  588. }
  589. NonnullRefPtr<Comment> Document::create_comment(const String& data)
  590. {
  591. return adopt_ref(*new Comment(*this, data));
  592. }
  593. NonnullRefPtr<Range> Document::create_range()
  594. {
  595. return Range::create(*this);
  596. }
  597. // https://dom.spec.whatwg.org/#dom-document-createevent
  598. NonnullRefPtr<Event> Document::create_event(const String& interface)
  599. {
  600. auto interface_lowercase = interface.to_lowercase();
  601. RefPtr<Event> event;
  602. if (interface_lowercase == "beforeunloadevent") {
  603. event = Event::create(""); // FIXME: Create BeforeUnloadEvent
  604. } else if (interface_lowercase == "compositionevent") {
  605. event = Event::create(""); // FIXME: Create CompositionEvent
  606. } else if (interface_lowercase == "customevent") {
  607. event = CustomEvent::create("");
  608. } else if (interface_lowercase == "devicemotionevent") {
  609. event = Event::create(""); // FIXME: Create DeviceMotionEvent
  610. } else if (interface_lowercase == "deviceorientationevent") {
  611. event = Event::create(""); // FIXME: Create DeviceOrientationEvent
  612. } else if (interface_lowercase == "dragevent") {
  613. event = Event::create(""); // FIXME: Create DragEvent
  614. } else if (interface_lowercase.is_one_of("event", "events")) {
  615. event = Event::create("");
  616. } else if (interface_lowercase == "focusevent") {
  617. event = UIEvents::FocusEvent::create("");
  618. } else if (interface_lowercase == "hashchangeevent") {
  619. event = Event::create(""); // FIXME: Create HashChangeEvent
  620. } else if (interface_lowercase == "htmlevents") {
  621. event = Event::create("");
  622. } else if (interface_lowercase == "keyboardevent") {
  623. event = UIEvents::KeyboardEvent::create("");
  624. } else if (interface_lowercase == "messageevent") {
  625. event = HTML::MessageEvent::create("");
  626. } else if (interface_lowercase.is_one_of("mouseevent", "mouseevents")) {
  627. event = UIEvents::MouseEvent::create("", 0, 0, 0, 0);
  628. } else if (interface_lowercase == "storageevent") {
  629. event = Event::create(""); // FIXME: Create StorageEvent
  630. } else if (interface_lowercase == "svgevents") {
  631. event = Event::create("");
  632. } else if (interface_lowercase == "textevent") {
  633. event = Event::create(""); // FIXME: Create CompositionEvent
  634. } else if (interface_lowercase == "touchevent") {
  635. event = Event::create(""); // FIXME: Create TouchEvent
  636. } else if (interface_lowercase.is_one_of("uievent", "uievents")) {
  637. event = UIEvents::UIEvent::create("");
  638. } else {
  639. // FIXME:
  640. // 3. If constructor is null, then throw a "NotSupportedError" DOMException.
  641. // 4. If the interface indicated by constructor is not exposed on the relevant global object of this, then throw a "NotSupportedError" DOMException.
  642. TODO();
  643. }
  644. // Setting type to empty string is handled by each constructor.
  645. // FIXME:
  646. // 7. Initialize event’s timeStamp attribute to a DOMHighResTimeStamp representing the high resolution time from the time origin to now.
  647. event->set_is_trusted(false);
  648. event->set_initialized(false);
  649. return event.release_nonnull();
  650. }
  651. void Document::set_pending_parsing_blocking_script(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement* script)
  652. {
  653. m_pending_parsing_blocking_script = script;
  654. }
  655. NonnullRefPtr<HTML::HTMLScriptElement> Document::take_pending_parsing_blocking_script(Badge<HTML::HTMLParser>)
  656. {
  657. return m_pending_parsing_blocking_script.release_nonnull();
  658. }
  659. void Document::add_script_to_execute_when_parsing_has_finished(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement& script)
  660. {
  661. m_scripts_to_execute_when_parsing_has_finished.append(script);
  662. }
  663. NonnullRefPtrVector<HTML::HTMLScriptElement> Document::take_scripts_to_execute_when_parsing_has_finished(Badge<HTML::HTMLParser>)
  664. {
  665. return move(m_scripts_to_execute_when_parsing_has_finished);
  666. }
  667. void Document::add_script_to_execute_as_soon_as_possible(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement& script)
  668. {
  669. m_scripts_to_execute_as_soon_as_possible.append(script);
  670. }
  671. NonnullRefPtrVector<HTML::HTMLScriptElement> Document::take_scripts_to_execute_as_soon_as_possible(Badge<HTML::HTMLParser>)
  672. {
  673. return move(m_scripts_to_execute_as_soon_as_possible);
  674. }
  675. // https://dom.spec.whatwg.org/#dom-document-importnode
  676. ExceptionOr<NonnullRefPtr<Node>> Document::import_node(NonnullRefPtr<Node> node, bool deep)
  677. {
  678. // 1. If node is a document or shadow root, then throw a "NotSupportedError" DOMException.
  679. if (is<Document>(*node) || is<ShadowRoot>(*node))
  680. return DOM::NotSupportedError::create("Cannot import a document or shadow root.");
  681. // 2. Return a clone of node, with this and the clone children flag set if deep is true.
  682. return node->clone_node(this, deep);
  683. }
  684. // https://dom.spec.whatwg.org/#concept-node-adopt
  685. void Document::adopt_node(Node& node)
  686. {
  687. auto& old_document = node.document();
  688. if (node.parent())
  689. node.remove();
  690. if (&old_document != this) {
  691. // FIXME: This should be shadow-including.
  692. node.for_each_in_inclusive_subtree([&](auto& inclusive_descendant) {
  693. inclusive_descendant.set_document({}, *this);
  694. // FIXME: If inclusiveDescendant is an element, then set the node document of each attribute in inclusiveDescendant’s attribute list to document.
  695. return IterationDecision::Continue;
  696. });
  697. // FIXME: For each inclusiveDescendant in node’s shadow-including inclusive descendants that is custom,
  698. // enqueue a custom element callback reaction with inclusiveDescendant, callback name "adoptedCallback",
  699. // and an argument list containing oldDocument and document.
  700. // FIXME: This should be shadow-including.
  701. node.for_each_in_inclusive_subtree([&](auto& inclusive_descendant) {
  702. inclusive_descendant.adopted_from(old_document);
  703. return IterationDecision::Continue;
  704. });
  705. }
  706. }
  707. // https://dom.spec.whatwg.org/#dom-document-adoptnode
  708. ExceptionOr<NonnullRefPtr<Node>> Document::adopt_node_binding(NonnullRefPtr<Node> node)
  709. {
  710. if (is<Document>(*node))
  711. return DOM::NotSupportedError::create("Cannot adopt a document into a document");
  712. if (is<ShadowRoot>(*node))
  713. return DOM::HierarchyRequestError::create("Cannot adopt a shadow root into a document");
  714. if (is<DocumentFragment>(*node) && verify_cast<DocumentFragment>(*node).host())
  715. return node;
  716. adopt_node(*node);
  717. return node;
  718. }
  719. const DocumentType* Document::doctype() const
  720. {
  721. return first_child_of_type<DocumentType>();
  722. }
  723. const String& Document::compat_mode() const
  724. {
  725. static String back_compat = "BackCompat";
  726. static String css1_compat = "CSS1Compat";
  727. if (m_quirks_mode == QuirksMode::Yes)
  728. return back_compat;
  729. return css1_compat;
  730. }
  731. bool Document::is_editable() const
  732. {
  733. return m_editable;
  734. }
  735. void Document::set_focused_element(Element* element)
  736. {
  737. if (m_focused_element == element)
  738. return;
  739. if (m_focused_element)
  740. m_focused_element->did_lose_focus();
  741. m_focused_element = element;
  742. if (m_focused_element)
  743. m_focused_element->did_receive_focus();
  744. if (m_layout_root)
  745. m_layout_root->set_needs_display();
  746. }
  747. void Document::set_active_element(Element* element)
  748. {
  749. if (m_active_element == element)
  750. return;
  751. m_active_element = element;
  752. if (m_layout_root)
  753. m_layout_root->set_needs_display();
  754. }
  755. String Document::ready_state() const
  756. {
  757. switch (m_readiness) {
  758. case HTML::DocumentReadyState::Loading:
  759. return "loading"sv;
  760. case HTML::DocumentReadyState::Interactive:
  761. return "interactive"sv;
  762. case HTML::DocumentReadyState::Complete:
  763. return "complete"sv;
  764. }
  765. VERIFY_NOT_REACHED();
  766. }
  767. // https://html.spec.whatwg.org/#update-the-current-document-readiness
  768. void Document::update_readiness(HTML::DocumentReadyState readiness_value)
  769. {
  770. // 1. If document's current document readiness equals readinessValue, then return.
  771. if (m_readiness == readiness_value)
  772. return;
  773. // The spec doesn't actually mention updating the current readiness value.
  774. // FIXME: https://github.com/whatwg/html/issues/7120
  775. m_readiness = readiness_value;
  776. // FIXME: 2. If document is associated with an HTML parser, then:
  777. // FIXME: 1. If document is associated with an HTML parser, then:
  778. // 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.
  779. // 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.
  780. // 3. Fire an event named readystatechange at document.
  781. dispatch_event(Event::create(HTML::EventNames::readystatechange));
  782. }
  783. Page* Document::page()
  784. {
  785. return m_browsing_context ? m_browsing_context->page() : nullptr;
  786. }
  787. const Page* Document::page() const
  788. {
  789. return m_browsing_context ? m_browsing_context->page() : nullptr;
  790. }
  791. EventTarget* Document::get_parent(const Event& event)
  792. {
  793. if (event.type() == HTML::EventNames::load)
  794. return nullptr;
  795. return &window();
  796. }
  797. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#completely-finish-loading
  798. void Document::completely_finish_loading()
  799. {
  800. // 1. Assert: document's browsing context is non-null.
  801. VERIFY(browsing_context());
  802. // FIXME: 2. Set document's completely loaded time to the current time.
  803. // 3. Let container be document's browsing context's container.
  804. auto* container = browsing_context()->container();
  805. // 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.
  806. if (container && is<HTML::HTMLIFrameElement>(*container)) {
  807. container->queue_an_element_task(HTML::Task::Source::DOMManipulation, [container]() mutable {
  808. run_iframe_load_event_steps(static_cast<HTML::HTMLIFrameElement&>(*container));
  809. });
  810. }
  811. // 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.
  812. else if (container) {
  813. container->queue_an_element_task(HTML::Task::Source::DOMManipulation, [container]() mutable {
  814. container->dispatch_event(DOM::Event::create(HTML::EventNames::load));
  815. });
  816. }
  817. }
  818. String Document::cookie(Cookie::Source source)
  819. {
  820. if (auto* page = this->page())
  821. return page->client().page_did_request_cookie(m_url, source);
  822. return {};
  823. }
  824. void Document::set_cookie(String cookie_string, Cookie::Source source)
  825. {
  826. auto cookie = Cookie::parse_cookie(cookie_string);
  827. if (!cookie.has_value())
  828. return;
  829. if (auto* page = this->page())
  830. page->client().page_did_set_cookie(m_url, cookie.value(), source);
  831. }
  832. String Document::dump_dom_tree_as_json() const
  833. {
  834. StringBuilder builder;
  835. JsonObjectSerializer json(builder);
  836. serialize_tree_as_json(json);
  837. json.finish();
  838. return builder.to_string();
  839. }
  840. // https://html.spec.whatwg.org/multipage/semantics.html#has-a-style-sheet-that-is-blocking-scripts
  841. bool Document::has_a_style_sheet_that_is_blocking_scripts() const
  842. {
  843. // A Document has a style sheet that is blocking scripts if its script-blocking style sheet counter is greater than 0,
  844. if (m_script_blocking_style_sheet_counter > 0)
  845. return true;
  846. // ...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.
  847. if (!browsing_context() || !browsing_context()->container_document())
  848. return false;
  849. return browsing_context()->container_document()->m_script_blocking_style_sheet_counter > 0;
  850. }
  851. String Document::referrer() const
  852. {
  853. // FIXME: Return the document's actual referrer.
  854. return "";
  855. }
  856. // https://html.spec.whatwg.org/multipage/browsers.html#fully-active
  857. bool Document::is_fully_active() const
  858. {
  859. // 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,
  860. // and either d's browsing context is a top-level browsing context, or d's browsing context's container document is fully active.
  861. return browsing_context() && browsing_context()->active_document() == this && (browsing_context()->is_top_level() || browsing_context()->container_document()->is_fully_active());
  862. }
  863. // https://html.spec.whatwg.org/multipage/browsers.html#active-document
  864. bool Document::is_active() const
  865. {
  866. // A browsing context's active document is its active window's associated Document.
  867. return browsing_context() && browsing_context()->active_document() == this;
  868. }
  869. // https://html.spec.whatwg.org/multipage/history.html#dom-document-location
  870. Bindings::LocationObject* Document::location()
  871. {
  872. // The Document object's location attribute's getter must return this Document object's relevant global object's Location object,
  873. // if this Document object is fully active, and null otherwise.
  874. if (!is_fully_active())
  875. return nullptr;
  876. return window().wrapper()->location_object();
  877. }
  878. // https://html.spec.whatwg.org/multipage/interaction.html#dom-document-hidden
  879. bool Document::hidden() const
  880. {
  881. return false;
  882. }
  883. // https://html.spec.whatwg.org/multipage/interaction.html#dom-document-visibilitystate
  884. String Document::visibility_state() const
  885. {
  886. return hidden() ? "hidden" : "visible";
  887. }
  888. // https://drafts.csswg.org/cssom-view/#run-the-resize-steps
  889. void Document::run_the_resize_steps()
  890. {
  891. // 1. If doc’s viewport has had its width or height changed
  892. // (e.g. as a result of the user resizing the browser window, or changing the page zoom scale factor,
  893. // or an iframe element’s dimensions are changed) since the last time these steps were run,
  894. // fire an event named resize at the Window object associated with doc.
  895. if (!browsing_context())
  896. return;
  897. auto viewport_size = browsing_context()->viewport_rect().size();
  898. if (m_last_viewport_size == viewport_size)
  899. return;
  900. m_last_viewport_size = viewport_size;
  901. dispatch_event(DOM::Event::create(UIEvents::EventNames::resize));
  902. update_layout();
  903. }
  904. void Document::add_media_query_list(NonnullRefPtr<CSS::MediaQueryList>& media_query_list)
  905. {
  906. m_media_query_lists.append(media_query_list);
  907. }
  908. // https://drafts.csswg.org/cssom-view/#evaluate-media-queries-and-report-changes
  909. void Document::evaluate_media_queries_and_report_changes()
  910. {
  911. // NOTE: Not in the spec, but we take this opportunity to prune null WeakPtrs.
  912. m_media_query_lists.remove_all_matching([](auto& it) {
  913. return it.is_null();
  914. });
  915. // 1. For each MediaQueryList object target that has doc as its document,
  916. // in the order they were created, oldest first, run these substeps:
  917. for (auto& media_query_list_ptr : m_media_query_lists) {
  918. // 1.1. If target’s matches state has changed since the last time these steps
  919. // were run, fire an event at target using the MediaQueryListEvent constructor,
  920. // with its type attribute initialized to change, its isTrusted attribute
  921. // initialized to true, its media attribute initialized to target’s media,
  922. // and its matches attribute initialized to target’s matches state.
  923. if (media_query_list_ptr.is_null())
  924. continue;
  925. auto media_query_list = media_query_list_ptr.strong_ref();
  926. bool did_match = media_query_list->matches();
  927. bool now_matches = media_query_list->evaluate();
  928. if (did_match != now_matches) {
  929. CSS::MediaQueryListEventInit init;
  930. init.media = media_query_list->media();
  931. init.matches = now_matches;
  932. auto event = CSS::MediaQueryListEvent::create(HTML::EventNames::change, init);
  933. event->set_is_trusted(true);
  934. media_query_list->dispatch_event(event);
  935. }
  936. }
  937. // Also not in the spec, but this is as good a place as any to evaluate @media rules!
  938. for (auto& style_sheet : style_sheets().sheets()) {
  939. style_sheet.evaluate_media_queries(window());
  940. }
  941. }
  942. NonnullRefPtr<DOMImplementation> Document::implementation() const
  943. {
  944. return *m_implementation;
  945. }
  946. bool Document::has_focus() const
  947. {
  948. // FIXME: Return whether we actually have focus.
  949. return true;
  950. }
  951. }