Document.cpp 34 KB

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