Document.cpp 40 KB

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