Document.cpp 40 KB

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