Document.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Linus Groh <mail@linusgroh.de>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/StringBuilder.h>
  8. #include <AK/Utf8View.h>
  9. #include <LibCore/Timer.h>
  10. #include <LibJS/Interpreter.h>
  11. #include <LibJS/Parser.h>
  12. #include <LibJS/Runtime/Function.h>
  13. #include <LibWeb/Bindings/MainThreadVM.h>
  14. #include <LibWeb/Bindings/WindowObject.h>
  15. #include <LibWeb/CSS/StyleResolver.h>
  16. #include <LibWeb/Cookie/ParsedCookie.h>
  17. #include <LibWeb/DOM/Comment.h>
  18. #include <LibWeb/DOM/DOMException.h>
  19. #include <LibWeb/DOM/Document.h>
  20. #include <LibWeb/DOM/DocumentFragment.h>
  21. #include <LibWeb/DOM/DocumentType.h>
  22. #include <LibWeb/DOM/Element.h>
  23. #include <LibWeb/DOM/ElementFactory.h>
  24. #include <LibWeb/DOM/Event.h>
  25. #include <LibWeb/DOM/ExceptionOr.h>
  26. #include <LibWeb/DOM/HTMLCollection.h>
  27. #include <LibWeb/DOM/Range.h>
  28. #include <LibWeb/DOM/ShadowRoot.h>
  29. #include <LibWeb/DOM/Text.h>
  30. #include <LibWeb/DOM/Window.h>
  31. #include <LibWeb/Dump.h>
  32. #include <LibWeb/HTML/AttributeNames.h>
  33. #include <LibWeb/HTML/EventNames.h>
  34. #include <LibWeb/HTML/HTMLBodyElement.h>
  35. #include <LibWeb/HTML/HTMLFrameSetElement.h>
  36. #include <LibWeb/HTML/HTMLHeadElement.h>
  37. #include <LibWeb/HTML/HTMLHtmlElement.h>
  38. #include <LibWeb/HTML/HTMLScriptElement.h>
  39. #include <LibWeb/HTML/HTMLTitleElement.h>
  40. #include <LibWeb/InProcessWebView.h>
  41. #include <LibWeb/Layout/BlockFormattingContext.h>
  42. #include <LibWeb/Layout/InitialContainingBlockBox.h>
  43. #include <LibWeb/Layout/TreeBuilder.h>
  44. #include <LibWeb/Namespace.h>
  45. #include <LibWeb/Origin.h>
  46. #include <LibWeb/Page/Frame.h>
  47. #include <LibWeb/SVG/TagNames.h>
  48. #include <LibWeb/UIEvents/MouseEvent.h>
  49. #include <ctype.h>
  50. namespace Web::DOM {
  51. Document::Document(const URL& url)
  52. : ParentNode(*this, NodeType::DOCUMENT_NODE)
  53. , m_style_resolver(make<CSS::StyleResolver>(*this))
  54. , m_style_sheets(CSS::StyleSheetList::create(*this))
  55. , m_url(url)
  56. , m_window(Window::create_with_document(*this))
  57. , m_implementation(DOMImplementation::create(*this))
  58. {
  59. m_style_update_timer = Core::Timer::create_single_shot(0, [this] {
  60. update_style();
  61. });
  62. m_forced_layout_timer = Core::Timer::create_single_shot(0, [this] {
  63. force_layout();
  64. });
  65. }
  66. Document::~Document()
  67. {
  68. }
  69. void Document::removed_last_ref()
  70. {
  71. VERIFY(!ref_count());
  72. VERIFY(!m_deletion_has_begun);
  73. if (m_referencing_node_count) {
  74. // The document has reached ref_count==0 but still has nodes keeping it alive.
  75. // At this point, sever all the node links we control.
  76. // If nodes remain elsewhere (e.g JS wrappers), they will keep the document alive.
  77. // NOTE: This makes sure we stay alive across for the duration of the cleanup below.
  78. increment_referencing_node_count();
  79. m_focused_element = nullptr;
  80. m_hovered_node = nullptr;
  81. m_pending_parsing_blocking_script = nullptr;
  82. m_inspected_node = nullptr;
  83. m_scripts_to_execute_when_parsing_has_finished.clear();
  84. m_scripts_to_execute_as_soon_as_possible.clear();
  85. m_associated_inert_template_document = nullptr;
  86. m_interpreter = nullptr;
  87. {
  88. // Gather up all the descendants of this document and prune them from the tree.
  89. // FIXME: This could definitely be more elegant.
  90. NonnullRefPtrVector<Node> descendants;
  91. for_each_in_inclusive_subtree([&](auto& node) {
  92. if (&node != this)
  93. descendants.append(node);
  94. return IterationDecision::Continue;
  95. });
  96. for (auto& node : descendants) {
  97. VERIFY(&node.document() == this);
  98. VERIFY(!node.is_document());
  99. if (node.parent())
  100. node.remove();
  101. }
  102. }
  103. m_in_removed_last_ref = false;
  104. decrement_referencing_node_count();
  105. return;
  106. }
  107. m_in_removed_last_ref = false;
  108. m_deletion_has_begun = true;
  109. delete this;
  110. }
  111. Origin Document::origin() const
  112. {
  113. if (!m_url.is_valid())
  114. return {};
  115. return { m_url.protocol(), m_url.host(), m_url.port() };
  116. }
  117. void Document::set_origin(const Origin& origin)
  118. {
  119. m_url.set_protocol(origin.protocol());
  120. m_url.set_host(origin.host());
  121. m_url.set_port(origin.port());
  122. }
  123. void Document::schedule_style_update()
  124. {
  125. if (m_style_update_timer->is_active())
  126. return;
  127. m_style_update_timer->start();
  128. }
  129. void Document::schedule_forced_layout()
  130. {
  131. if (m_forced_layout_timer->is_active())
  132. return;
  133. m_forced_layout_timer->start();
  134. }
  135. bool Document::is_child_allowed(const Node& node) const
  136. {
  137. switch (node.type()) {
  138. case NodeType::DOCUMENT_NODE:
  139. case NodeType::TEXT_NODE:
  140. return false;
  141. case NodeType::COMMENT_NODE:
  142. return true;
  143. case NodeType::DOCUMENT_TYPE_NODE:
  144. return !first_child_of_type<DocumentType>();
  145. case NodeType::ELEMENT_NODE:
  146. return !first_child_of_type<Element>();
  147. default:
  148. return false;
  149. }
  150. }
  151. Element* Document::document_element()
  152. {
  153. return first_child_of_type<Element>();
  154. }
  155. const Element* Document::document_element() const
  156. {
  157. return first_child_of_type<Element>();
  158. }
  159. const HTML::HTMLHtmlElement* Document::html_element() const
  160. {
  161. auto* html = document_element();
  162. if (is<HTML::HTMLHtmlElement>(html))
  163. return downcast<HTML::HTMLHtmlElement>(html);
  164. return nullptr;
  165. }
  166. const HTML::HTMLHeadElement* Document::head() const
  167. {
  168. auto* html = html_element();
  169. if (!html)
  170. return nullptr;
  171. return html->first_child_of_type<HTML::HTMLHeadElement>();
  172. }
  173. const HTML::HTMLElement* Document::body() const
  174. {
  175. auto* html = html_element();
  176. if (!html)
  177. return nullptr;
  178. auto* first_body = html->first_child_of_type<HTML::HTMLBodyElement>();
  179. if (first_body)
  180. return first_body;
  181. auto* first_frameset = html->first_child_of_type<HTML::HTMLFrameSetElement>();
  182. if (first_frameset)
  183. return first_frameset;
  184. return nullptr;
  185. }
  186. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-body
  187. ExceptionOr<void> Document::set_body(HTML::HTMLElement& new_body)
  188. {
  189. if (!is<HTML::HTMLBodyElement>(new_body) && !is<HTML::HTMLFrameSetElement>(new_body))
  190. return DOM::HierarchyRequestError::create("Invalid document body element, must be 'body' or 'frameset'");
  191. auto* existing_body = body();
  192. if (existing_body) {
  193. TODO();
  194. return {};
  195. }
  196. auto* document_element = this->document_element();
  197. if (!document_element)
  198. return DOM::HierarchyRequestError::create("Missing document element");
  199. document_element->append_child(new_body);
  200. return {};
  201. }
  202. String Document::title() const
  203. {
  204. auto* head_element = head();
  205. if (!head_element)
  206. return {};
  207. auto* title_element = head_element->first_child_of_type<HTML::HTMLTitleElement>();
  208. if (!title_element)
  209. return {};
  210. auto raw_title = title_element->text_content();
  211. StringBuilder builder;
  212. bool last_was_space = false;
  213. for (auto code_point : Utf8View(raw_title)) {
  214. if (isspace(code_point)) {
  215. last_was_space = true;
  216. } else {
  217. if (last_was_space && !builder.is_empty())
  218. builder.append(' ');
  219. builder.append_code_point(code_point);
  220. last_was_space = false;
  221. }
  222. }
  223. return builder.to_string();
  224. }
  225. void Document::set_title(const String& title)
  226. {
  227. auto* head_element = const_cast<HTML::HTMLHeadElement*>(head());
  228. if (!head_element)
  229. return;
  230. RefPtr<HTML::HTMLTitleElement> title_element = head_element->first_child_of_type<HTML::HTMLTitleElement>();
  231. if (!title_element) {
  232. title_element = static_ptr_cast<HTML::HTMLTitleElement>(create_element(HTML::TagNames::title));
  233. head_element->append_child(*title_element);
  234. }
  235. title_element->remove_all_children(true);
  236. title_element->append_child(adopt(*new Text(*this, title)));
  237. if (auto* page = this->page()) {
  238. if (frame() == &page->main_frame())
  239. page->client().page_did_change_title(title);
  240. }
  241. }
  242. void Document::attach_to_frame(Badge<Frame>, Frame& frame)
  243. {
  244. m_frame = frame;
  245. update_layout();
  246. }
  247. void Document::detach_from_frame(Badge<Frame>, Frame& frame)
  248. {
  249. VERIFY(&frame == m_frame);
  250. tear_down_layout_tree();
  251. m_frame = nullptr;
  252. }
  253. void Document::tear_down_layout_tree()
  254. {
  255. if (!m_layout_root)
  256. return;
  257. // Gather up all the layout nodes in a vector and detach them from parents
  258. // while the vector keeps them alive.
  259. NonnullRefPtrVector<Layout::Node> layout_nodes;
  260. m_layout_root->for_each_in_inclusive_subtree([&](auto& layout_node) {
  261. layout_nodes.append(layout_node);
  262. return IterationDecision::Continue;
  263. });
  264. for (auto& layout_node : layout_nodes) {
  265. if (layout_node.parent())
  266. layout_node.parent()->remove_child(layout_node);
  267. }
  268. m_layout_root = nullptr;
  269. }
  270. Color Document::background_color(const Palette& palette) const
  271. {
  272. auto default_color = palette.base();
  273. auto* body_element = body();
  274. if (!body_element)
  275. return default_color;
  276. auto* body_layout_node = body_element->layout_node();
  277. if (!body_layout_node)
  278. return default_color;
  279. auto color = body_layout_node->computed_values().background_color();
  280. if (!color.alpha())
  281. return default_color;
  282. return color;
  283. }
  284. RefPtr<Gfx::Bitmap> Document::background_image() const
  285. {
  286. auto* body_element = body();
  287. if (!body_element)
  288. return {};
  289. auto* body_layout_node = body_element->layout_node();
  290. if (!body_layout_node)
  291. return {};
  292. auto background_image = body_layout_node->background_image();
  293. if (!background_image)
  294. return {};
  295. return background_image->bitmap();
  296. }
  297. CSS::Repeat Document::background_repeat_x() const
  298. {
  299. auto* body_element = body();
  300. if (!body_element)
  301. return CSS::Repeat::Repeat;
  302. auto* body_layout_node = body_element->layout_node();
  303. if (!body_layout_node)
  304. return CSS::Repeat::Repeat;
  305. return body_layout_node->computed_values().background_repeat_x();
  306. }
  307. CSS::Repeat Document::background_repeat_y() const
  308. {
  309. auto* body_element = body();
  310. if (!body_element)
  311. return CSS::Repeat::Repeat;
  312. auto* body_layout_node = body_element->layout_node();
  313. if (!body_layout_node)
  314. return CSS::Repeat::Repeat;
  315. return body_layout_node->computed_values().background_repeat_y();
  316. }
  317. URL Document::complete_url(const String& string) const
  318. {
  319. return m_url.complete_url(string);
  320. }
  321. void Document::invalidate_layout()
  322. {
  323. tear_down_layout_tree();
  324. }
  325. void Document::force_layout()
  326. {
  327. invalidate_layout();
  328. update_layout();
  329. }
  330. void Document::update_layout()
  331. {
  332. if (!frame())
  333. return;
  334. if (!m_layout_root) {
  335. Layout::TreeBuilder tree_builder;
  336. m_layout_root = static_ptr_cast<Layout::InitialContainingBlockBox>(tree_builder.build(*this));
  337. }
  338. Layout::BlockFormattingContext root_formatting_context(*m_layout_root, nullptr);
  339. root_formatting_context.run(*m_layout_root, Layout::LayoutMode::Default);
  340. m_layout_root->set_needs_display();
  341. if (frame()->is_main_frame()) {
  342. if (auto* page = this->page())
  343. page->client().page_did_layout();
  344. }
  345. }
  346. static void update_style_recursively(DOM::Node& node)
  347. {
  348. node.for_each_child([&](auto& child) {
  349. if (child.needs_style_update()) {
  350. if (is<Element>(child))
  351. downcast<Element>(child).recompute_style();
  352. child.set_needs_style_update(false);
  353. }
  354. if (child.child_needs_style_update()) {
  355. update_style_recursively(child);
  356. child.set_child_needs_style_update(false);
  357. }
  358. return IterationDecision::Continue;
  359. });
  360. }
  361. void Document::update_style()
  362. {
  363. update_style_recursively(*this);
  364. update_layout();
  365. }
  366. RefPtr<Layout::Node> Document::create_layout_node()
  367. {
  368. return adopt(*new Layout::InitialContainingBlockBox(*this, CSS::StyleProperties::create()));
  369. }
  370. void Document::set_link_color(Color color)
  371. {
  372. m_link_color = color;
  373. }
  374. void Document::set_active_link_color(Color color)
  375. {
  376. m_active_link_color = color;
  377. }
  378. void Document::set_visited_link_color(Color color)
  379. {
  380. m_visited_link_color = color;
  381. }
  382. const Layout::InitialContainingBlockBox* Document::layout_node() const
  383. {
  384. return static_cast<const Layout::InitialContainingBlockBox*>(Node::layout_node());
  385. }
  386. Layout::InitialContainingBlockBox* Document::layout_node()
  387. {
  388. return static_cast<Layout::InitialContainingBlockBox*>(Node::layout_node());
  389. }
  390. void Document::set_inspected_node(Node* node)
  391. {
  392. if (m_inspected_node == node)
  393. return;
  394. if (m_inspected_node && m_inspected_node->layout_node())
  395. m_inspected_node->layout_node()->set_needs_display();
  396. m_inspected_node = node;
  397. if (m_inspected_node && m_inspected_node->layout_node())
  398. m_inspected_node->layout_node()->set_needs_display();
  399. }
  400. void Document::set_hovered_node(Node* node)
  401. {
  402. if (m_hovered_node == node)
  403. return;
  404. RefPtr<Node> old_hovered_node = move(m_hovered_node);
  405. m_hovered_node = node;
  406. invalidate_style();
  407. }
  408. NonnullRefPtr<HTMLCollection> Document::get_elements_by_name(String const& name)
  409. {
  410. return HTMLCollection::create(*this, [name](Element const& element) {
  411. return element.name() == name;
  412. });
  413. }
  414. NonnullRefPtr<HTMLCollection> Document::get_elements_by_tag_name(FlyString const& tag_name)
  415. {
  416. // FIXME: Support "*" for tag_name
  417. // https://dom.spec.whatwg.org/#concept-getelementsbytagname
  418. return HTMLCollection::create(*this, [tag_name](Element const& element) {
  419. if (element.namespace_() == Namespace::HTML)
  420. return element.local_name().to_lowercase() == tag_name.to_lowercase();
  421. return element.local_name() == tag_name;
  422. });
  423. }
  424. NonnullRefPtr<HTMLCollection> Document::get_elements_by_class_name(FlyString const& class_name)
  425. {
  426. return HTMLCollection::create(*this, [class_name, quirks_mode = document().in_quirks_mode()](Element const& element) {
  427. return element.has_class(class_name, quirks_mode ? CaseSensitivity::CaseInsensitive : CaseSensitivity::CaseSensitive);
  428. });
  429. }
  430. NonnullRefPtr<HTMLCollection> Document::applets()
  431. {
  432. // FIXME: This should return the same HTMLCollection object every time,
  433. // but that would cause a reference cycle since HTMLCollection refs the root.
  434. return HTMLCollection::create(*this, [] { return false; });
  435. }
  436. Color Document::link_color() const
  437. {
  438. if (m_link_color.has_value())
  439. return m_link_color.value();
  440. if (!page())
  441. return Color::Blue;
  442. return page()->palette().link();
  443. }
  444. Color Document::active_link_color() const
  445. {
  446. if (m_active_link_color.has_value())
  447. return m_active_link_color.value();
  448. if (!page())
  449. return Color::Red;
  450. return page()->palette().active_link();
  451. }
  452. Color Document::visited_link_color() const
  453. {
  454. if (m_visited_link_color.has_value())
  455. return m_visited_link_color.value();
  456. if (!page())
  457. return Color::Magenta;
  458. return page()->palette().visited_link();
  459. }
  460. JS::Interpreter& Document::interpreter()
  461. {
  462. if (!m_interpreter) {
  463. auto& vm = Bindings::main_thread_vm();
  464. // TODO: Hook up vm.on_promise_unhandled_rejection and vm.on_promise_rejection_handled
  465. // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#promise_rejection_events
  466. m_interpreter = JS::Interpreter::create<Bindings::WindowObject>(vm, *m_window);
  467. }
  468. return *m_interpreter;
  469. }
  470. JS::Value Document::run_javascript(const StringView& source, const StringView& filename)
  471. {
  472. auto parser = JS::Parser(JS::Lexer(source, filename));
  473. auto program = parser.parse_program();
  474. if (parser.has_errors()) {
  475. parser.print_errors();
  476. return JS::js_undefined();
  477. }
  478. auto& interpreter = document().interpreter();
  479. auto& vm = interpreter.vm();
  480. interpreter.run(interpreter.global_object(), *program);
  481. if (vm.exception())
  482. vm.clear_exception();
  483. return vm.last_value();
  484. }
  485. // https://dom.spec.whatwg.org/#dom-document-createelement
  486. // FIXME: This only implements step 6 of the algorithm and does not take in options.
  487. NonnullRefPtr<Element> Document::create_element(const String& tag_name)
  488. {
  489. // 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.
  490. return DOM::create_element(*this, tag_name, Namespace::HTML);
  491. }
  492. // https://dom.spec.whatwg.org/#internal-createelementns-steps
  493. // FIXME: This only implements step 4 of the algorithm and does not take in options.
  494. NonnullRefPtr<Element> Document::create_element_ns(const String& namespace_, const String& qualified_name)
  495. {
  496. return DOM::create_element(*this, qualified_name, namespace_);
  497. }
  498. NonnullRefPtr<DocumentFragment> Document::create_document_fragment()
  499. {
  500. return adopt(*new DocumentFragment(*this));
  501. }
  502. NonnullRefPtr<Text> Document::create_text_node(const String& data)
  503. {
  504. return adopt(*new Text(*this, data));
  505. }
  506. NonnullRefPtr<Comment> Document::create_comment(const String& data)
  507. {
  508. return adopt(*new Comment(*this, data));
  509. }
  510. NonnullRefPtr<Range> Document::create_range()
  511. {
  512. return Range::create(*this);
  513. }
  514. // https://dom.spec.whatwg.org/#dom-document-createevent
  515. NonnullRefPtr<Event> Document::create_event(const String& interface)
  516. {
  517. auto interface_lowercase = interface.to_lowercase();
  518. RefPtr<Event> event;
  519. if (interface_lowercase == "beforeunloadevent") {
  520. event = Event::create(""); // FIXME: Create BeforeUnloadEvent
  521. } else if (interface_lowercase == "compositionevent") {
  522. event = Event::create(""); // FIXME: Create CompositionEvent
  523. } else if (interface_lowercase == "customevent") {
  524. event = Event::create(""); // FIXME: Create CustomEvent
  525. } else if (interface_lowercase == "devicemotionevent") {
  526. event = Event::create(""); // FIXME: Create DeviceMotionEvent
  527. } else if (interface_lowercase == "deviceorientationevent") {
  528. event = Event::create(""); // FIXME: Create DeviceOrientationEvent
  529. } else if (interface_lowercase == "dragevent") {
  530. event = Event::create(""); // FIXME: Create DragEvent
  531. } else if (interface_lowercase.is_one_of("event", "events")) {
  532. event = Event::create("");
  533. } else if (interface_lowercase == "focusevent") {
  534. event = Event::create(""); // FIXME: Create FocusEvent
  535. } else if (interface_lowercase == "hashchangeevent") {
  536. event = Event::create(""); // FIXME: Create HashChangeEvent
  537. } else if (interface_lowercase == "htmlevents") {
  538. event = Event::create("");
  539. } else if (interface_lowercase == "keyboardevent") {
  540. event = Event::create(""); // FIXME: Create KeyboardEvent
  541. } else if (interface_lowercase == "messageevent") {
  542. event = Event::create(""); // FIXME: Create MessageEvent
  543. } else if (interface_lowercase.is_one_of("mouseevent", "mouseevents")) {
  544. event = UIEvents::MouseEvent::create("", 0, 0, 0, 0);
  545. } else if (interface_lowercase == "storageevent") {
  546. event = Event::create(""); // FIXME: Create StorageEvent
  547. } else if (interface_lowercase == "svgevents") {
  548. event = Event::create("");
  549. } else if (interface_lowercase == "textevent") {
  550. event = Event::create(""); // FIXME: Create CompositionEvent
  551. } else if (interface_lowercase == "touchevent") {
  552. event = Event::create(""); // FIXME: Create TouchEvent
  553. } else if (interface_lowercase.is_one_of("uievent", "uievents")) {
  554. event = UIEvents::UIEvent::create("");
  555. } else {
  556. // FIXME:
  557. // 3. If constructor is null, then throw a "NotSupportedError" DOMException.
  558. // 4. If the interface indicated by constructor is not exposed on the relevant global object of this, then throw a "NotSupportedError" DOMException.
  559. TODO();
  560. }
  561. // Setting type to empty string is handled by each constructor.
  562. // FIXME:
  563. // 7. Initialize event’s timeStamp attribute to a DOMHighResTimeStamp representing the high resolution time from the time origin to now.
  564. event->set_is_trusted(false);
  565. event->set_initialized(false);
  566. return event.release_nonnull();
  567. }
  568. void Document::set_pending_parsing_blocking_script(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement* script)
  569. {
  570. m_pending_parsing_blocking_script = script;
  571. }
  572. NonnullRefPtr<HTML::HTMLScriptElement> Document::take_pending_parsing_blocking_script(Badge<HTML::HTMLDocumentParser>)
  573. {
  574. return m_pending_parsing_blocking_script.release_nonnull();
  575. }
  576. void Document::add_script_to_execute_when_parsing_has_finished(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement& script)
  577. {
  578. m_scripts_to_execute_when_parsing_has_finished.append(script);
  579. }
  580. NonnullRefPtrVector<HTML::HTMLScriptElement> Document::take_scripts_to_execute_when_parsing_has_finished(Badge<HTML::HTMLDocumentParser>)
  581. {
  582. return move(m_scripts_to_execute_when_parsing_has_finished);
  583. }
  584. void Document::add_script_to_execute_as_soon_as_possible(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement& script)
  585. {
  586. m_scripts_to_execute_as_soon_as_possible.append(script);
  587. }
  588. NonnullRefPtrVector<HTML::HTMLScriptElement> Document::take_scripts_to_execute_as_soon_as_possible(Badge<HTML::HTMLDocumentParser>)
  589. {
  590. return move(m_scripts_to_execute_as_soon_as_possible);
  591. }
  592. // https://dom.spec.whatwg.org/#concept-node-adopt
  593. void Document::adopt_node(Node& node)
  594. {
  595. auto& old_document = node.document();
  596. if (node.parent())
  597. node.remove();
  598. if (&old_document != this) {
  599. // FIXME: This should be shadow-including.
  600. node.for_each_in_inclusive_subtree([&](auto& inclusive_descendant) {
  601. inclusive_descendant.set_document({}, *this);
  602. // FIXME: If inclusiveDescendant is an element, then set the node document of each attribute in inclusiveDescendant’s attribute list to document.
  603. return IterationDecision::Continue;
  604. });
  605. // FIXME: For each inclusiveDescendant in node’s shadow-including inclusive descendants that is custom,
  606. // enqueue a custom element callback reaction with inclusiveDescendant, callback name "adoptedCallback",
  607. // and an argument list containing oldDocument and document.
  608. // FIXME: This should be shadow-including.
  609. node.for_each_in_inclusive_subtree([&](auto& inclusive_descendant) {
  610. inclusive_descendant.adopted_from(old_document);
  611. return IterationDecision::Continue;
  612. });
  613. }
  614. }
  615. // https://dom.spec.whatwg.org/#dom-document-adoptnode
  616. ExceptionOr<NonnullRefPtr<Node>> Document::adopt_node_binding(NonnullRefPtr<Node> node)
  617. {
  618. if (is<Document>(*node))
  619. return DOM ::NotSupportedError::create("Cannot adopt a document into a document");
  620. if (is<ShadowRoot>(*node))
  621. return DOM::HierarchyRequestError::create("Cannot adopt a shadow root into a document");
  622. if (is<DocumentFragment>(*node) && downcast<DocumentFragment>(*node).host())
  623. return node;
  624. adopt_node(*node);
  625. return node;
  626. }
  627. const DocumentType* Document::doctype() const
  628. {
  629. return first_child_of_type<DocumentType>();
  630. }
  631. const String& Document::compat_mode() const
  632. {
  633. static String back_compat = "BackCompat";
  634. static String css1_compat = "CSS1Compat";
  635. if (m_quirks_mode == QuirksMode::Yes)
  636. return back_compat;
  637. return css1_compat;
  638. }
  639. bool Document::is_editable() const
  640. {
  641. return m_editable;
  642. }
  643. void Document::set_focused_element(Element* element)
  644. {
  645. if (m_focused_element == element)
  646. return;
  647. m_focused_element = element;
  648. if (m_layout_root)
  649. m_layout_root->set_needs_display();
  650. }
  651. void Document::set_ready_state(const String& ready_state)
  652. {
  653. m_ready_state = ready_state;
  654. dispatch_event(Event::create(HTML::EventNames::readystatechange));
  655. }
  656. Page* Document::page()
  657. {
  658. return m_frame ? m_frame->page() : nullptr;
  659. }
  660. const Page* Document::page() const
  661. {
  662. return m_frame ? m_frame->page() : nullptr;
  663. }
  664. EventTarget* Document::get_parent(const Event& event)
  665. {
  666. if (event.type() == HTML::EventNames::load)
  667. return nullptr;
  668. return &window();
  669. }
  670. void Document::completely_finish_loading()
  671. {
  672. // FIXME: This needs to handle iframes.
  673. dispatch_event(DOM::Event::create(HTML::EventNames::load));
  674. }
  675. String Document::cookie(Cookie::Source source)
  676. {
  677. if (auto* page = this->page())
  678. return page->client().page_did_request_cookie(m_url, source);
  679. return {};
  680. }
  681. void Document::set_cookie(String cookie_string, Cookie::Source source)
  682. {
  683. auto cookie = Cookie::parse_cookie(cookie_string);
  684. if (!cookie.has_value())
  685. return;
  686. if (auto* page = this->page())
  687. page->client().page_did_set_cookie(m_url, cookie.value(), source);
  688. }
  689. }