Document.cpp 39 KB

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