Element.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/AnyOf.h>
  7. #include <AK/CharacterTypes.h>
  8. #include <AK/Debug.h>
  9. #include <AK/StringBuilder.h>
  10. #include <LibWeb/CSS/Parser/Parser.h>
  11. #include <LibWeb/CSS/PropertyID.h>
  12. #include <LibWeb/CSS/ResolvedCSSStyleDeclaration.h>
  13. #include <LibWeb/CSS/SelectorEngine.h>
  14. #include <LibWeb/DOM/DOMException.h>
  15. #include <LibWeb/DOM/DOMTokenList.h>
  16. #include <LibWeb/DOM/Document.h>
  17. #include <LibWeb/DOM/Element.h>
  18. #include <LibWeb/DOM/ExceptionOr.h>
  19. #include <LibWeb/DOM/HTMLCollection.h>
  20. #include <LibWeb/DOM/ShadowRoot.h>
  21. #include <LibWeb/DOM/Text.h>
  22. #include <LibWeb/DOMParsing/InnerHTML.h>
  23. #include <LibWeb/Geometry/DOMRect.h>
  24. #include <LibWeb/Geometry/DOMRectList.h>
  25. #include <LibWeb/HTML/BrowsingContext.h>
  26. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  27. #include <LibWeb/HTML/Parser/HTMLParser.h>
  28. #include <LibWeb/Layout/BlockContainer.h>
  29. #include <LibWeb/Layout/InlineNode.h>
  30. #include <LibWeb/Layout/ListItemBox.h>
  31. #include <LibWeb/Layout/TableBox.h>
  32. #include <LibWeb/Layout/TableCellBox.h>
  33. #include <LibWeb/Layout/TableRowBox.h>
  34. #include <LibWeb/Layout/TableRowGroupBox.h>
  35. #include <LibWeb/Layout/TreeBuilder.h>
  36. #include <LibWeb/Namespace.h>
  37. #include <LibWeb/Painting/PaintableBox.h>
  38. namespace Web::DOM {
  39. Element::Element(Document& document, DOM::QualifiedName qualified_name)
  40. : ParentNode(document, NodeType::ELEMENT_NODE)
  41. , m_qualified_name(move(qualified_name))
  42. , m_attributes(NamedNodeMap::create(*this))
  43. {
  44. make_html_uppercased_qualified_name();
  45. }
  46. Element::~Element()
  47. {
  48. }
  49. // https://dom.spec.whatwg.org/#dom-element-getattribute
  50. String Element::get_attribute(const FlyString& name) const
  51. {
  52. // 1. Let attr be the result of getting an attribute given qualifiedName and this.
  53. auto const* attribute = m_attributes->get_attribute(name);
  54. // 2. If attr is null, return null.
  55. if (!attribute)
  56. return {};
  57. // 3. Return attr’s value.
  58. return attribute->value();
  59. }
  60. // https://dom.spec.whatwg.org/#dom-element-setattribute
  61. ExceptionOr<void> Element::set_attribute(const FlyString& name, const String& value)
  62. {
  63. // 1. If qualifiedName does not match the Name production in XML, then throw an "InvalidCharacterError" DOMException.
  64. // FIXME: Proper name validation
  65. if (name.is_empty())
  66. return InvalidCharacterError::create("Attribute name must not be empty");
  67. // 2. If this is in the HTML namespace and its node document is an HTML document, then set qualifiedName to qualifiedName in ASCII lowercase.
  68. // FIXME: Handle the second condition, assume it is an HTML document for now.
  69. bool insert_as_lowercase = namespace_uri() == Namespace::HTML;
  70. // 3. Let attribute be the first attribute in this’s attribute list whose qualified name is qualifiedName, and null otherwise.
  71. auto* attribute = m_attributes->get_attribute(name);
  72. // 4. If attribute is null, create an attribute whose local name is qualifiedName, value is value, and node document is this’s node document, then append this attribute to this, and then return.
  73. if (!attribute) {
  74. auto new_attribute = Attribute::create(document(), insert_as_lowercase ? name.to_lowercase() : name, value);
  75. m_attributes->append_attribute(new_attribute);
  76. attribute = new_attribute.ptr();
  77. }
  78. // 5. Change attribute to value.
  79. else {
  80. attribute->set_value(value);
  81. }
  82. parse_attribute(attribute->local_name(), value);
  83. // FIXME: Invalidate less.
  84. document().invalidate_style();
  85. return {};
  86. }
  87. // https://dom.spec.whatwg.org/#validate-and-extract
  88. ExceptionOr<QualifiedName> validate_and_extract(FlyString namespace_, FlyString qualified_name)
  89. {
  90. // 1. If namespace is the empty string, then set it to null.
  91. if (namespace_.is_empty())
  92. namespace_ = {};
  93. // 2. Validate qualifiedName.
  94. if (auto result = Document::validate_qualified_name(qualified_name); result.is_exception())
  95. return result.exception();
  96. // 3. Let prefix be null.
  97. FlyString prefix = {};
  98. // 4. Let localName be qualifiedName.
  99. auto local_name = qualified_name;
  100. // 5. If qualifiedName contains a U+003A (:), then strictly split the string on it and set prefix to the part before and localName to the part after.
  101. if (qualified_name.view().contains(':')) {
  102. auto parts = qualified_name.view().split_view(':');
  103. prefix = parts[0];
  104. local_name = parts[1];
  105. }
  106. // 6. If prefix is non-null and namespace is null, then throw a "NamespaceError" DOMException.
  107. if (!prefix.is_null() && namespace_.is_null())
  108. return NamespaceError::create("Prefix is non-null and namespace is null.");
  109. // 7. If prefix is "xml" and namespace is not the XML namespace, then throw a "NamespaceError" DOMException.
  110. if (prefix == "xml"sv && namespace_ != Namespace::XML)
  111. return NamespaceError::create("Prefix is 'xml' and namespace is not the XML namespace.");
  112. // 8. If either qualifiedName or prefix is "xmlns" and namespace is not the XMLNS namespace, then throw a "NamespaceError" DOMException.
  113. if ((qualified_name == "xmlns"sv || prefix == "xmlns"sv) && namespace_ != Namespace::XMLNS)
  114. return NamespaceError::create("Either qualifiedName or prefix is 'xmlns' and namespace is not the XMLNS namespace.");
  115. // 9. If namespace is the XMLNS namespace and neither qualifiedName nor prefix is "xmlns", then throw a "NamespaceError" DOMException.
  116. if (namespace_ == Namespace::XMLNS && !(qualified_name == "xmlns"sv || prefix == "xmlns"sv))
  117. return NamespaceError::create("Namespace is the XMLNS namespace and neither qualifiedName nor prefix is 'xmlns'.");
  118. // 10. Return namespace, prefix, and localName.
  119. return QualifiedName { local_name, prefix, namespace_ };
  120. }
  121. // https://dom.spec.whatwg.org/#dom-element-setattributens
  122. ExceptionOr<void> Element::set_attribute_ns(FlyString const& namespace_, FlyString const& qualified_name, String const& value)
  123. {
  124. // 1. Let namespace, prefix, and localName be the result of passing namespace and qualifiedName to validate and extract.
  125. auto result = validate_and_extract(namespace_, qualified_name);
  126. if (result.is_exception())
  127. return result.exception();
  128. // FIXME: 2. Set an attribute value for this using localName, value, and also prefix and namespace.
  129. // FIXME: Don't just call through to setAttribute() here.
  130. return set_attribute(result.value().local_name(), value);
  131. }
  132. // https://dom.spec.whatwg.org/#dom-element-removeattribute
  133. void Element::remove_attribute(const FlyString& name)
  134. {
  135. m_attributes->remove_attribute(name);
  136. did_remove_attribute(name);
  137. // FIXME: Invalidate less.
  138. document().invalidate_style();
  139. }
  140. // https://dom.spec.whatwg.org/#dom-element-hasattribute
  141. bool Element::has_attribute(const FlyString& name) const
  142. {
  143. return m_attributes->get_attribute(name) != nullptr;
  144. }
  145. // https://dom.spec.whatwg.org/#dom-element-getattributenames
  146. Vector<String> Element::get_attribute_names() const
  147. {
  148. // The getAttributeNames() method steps are to return the qualified names of the attributes in this’s attribute list, in order; otherwise a new list.
  149. Vector<String> names;
  150. for (size_t i = 0; i < m_attributes->length(); ++i) {
  151. auto const* attribute = m_attributes->item(i);
  152. names.append(attribute->name());
  153. }
  154. return names;
  155. }
  156. bool Element::has_class(const FlyString& class_name, CaseSensitivity case_sensitivity) const
  157. {
  158. return any_of(m_classes, [&](auto& it) {
  159. return case_sensitivity == CaseSensitivity::CaseSensitive
  160. ? it == class_name
  161. : it.equals_ignoring_case(class_name);
  162. });
  163. }
  164. RefPtr<Layout::Node> Element::create_layout_node(NonnullRefPtr<CSS::StyleProperties> style)
  165. {
  166. if (local_name() == "noscript" && document().is_scripting_enabled())
  167. return nullptr;
  168. auto display = style->display();
  169. return create_layout_node_for_display_type(document(), display, move(style), this);
  170. }
  171. RefPtr<Layout::Node> Element::create_layout_node_for_display_type(DOM::Document& document, CSS::Display const& display, NonnullRefPtr<CSS::StyleProperties> style, Element* element)
  172. {
  173. if (display.is_table_inside())
  174. return adopt_ref(*new Layout::TableBox(document, element, move(style)));
  175. if (display.is_list_item())
  176. return adopt_ref(*new Layout::ListItemBox(document, element, move(style)));
  177. if (display.is_table_row())
  178. return adopt_ref(*new Layout::TableRowBox(document, element, move(style)));
  179. if (display.is_table_cell())
  180. return adopt_ref(*new Layout::TableCellBox(document, element, move(style)));
  181. if (display.is_table_row_group() || display.is_table_header_group() || display.is_table_footer_group())
  182. return adopt_ref(*new Layout::TableRowGroupBox(document, element, move(style)));
  183. if (display.is_table_column() || display.is_table_column_group() || display.is_table_caption()) {
  184. // FIXME: This is just an incorrect placeholder until we improve table layout support.
  185. return adopt_ref(*new Layout::BlockContainer(document, element, move(style)));
  186. }
  187. if (display.is_inline_outside()) {
  188. if (display.is_flow_root_inside()) {
  189. auto block = adopt_ref(*new Layout::BlockContainer(document, element, move(style)));
  190. block->set_inline(true);
  191. return block;
  192. }
  193. if (display.is_flow_inside())
  194. return adopt_ref(*new Layout::InlineNode(document, element, move(style)));
  195. dbgln_if(LIBWEB_CSS_DEBUG, "FIXME: Support display: {}", display.to_string());
  196. return adopt_ref(*new Layout::InlineNode(document, element, move(style)));
  197. }
  198. if (display.is_flow_inside() || display.is_flow_root_inside() || display.is_flex_inside())
  199. return adopt_ref(*new Layout::BlockContainer(document, element, move(style)));
  200. TODO();
  201. }
  202. void Element::parse_attribute(const FlyString& name, const String& value)
  203. {
  204. if (name == HTML::AttributeNames::class_) {
  205. auto new_classes = value.split_view(is_ascii_space);
  206. m_classes.clear();
  207. m_classes.ensure_capacity(new_classes.size());
  208. for (auto& new_class : new_classes) {
  209. m_classes.unchecked_append(new_class);
  210. }
  211. if (m_class_list)
  212. m_class_list->associated_attribute_changed(value);
  213. } else if (name == HTML::AttributeNames::style) {
  214. auto parsed_style = parse_css_declaration(CSS::ParsingContext(document()), value);
  215. if (!parsed_style.is_null()) {
  216. m_inline_style = CSS::ElementInlineCSSStyleDeclaration::create_and_take_properties_from(*this, parsed_style.release_nonnull());
  217. set_needs_style_update(true);
  218. }
  219. }
  220. }
  221. void Element::recompute_style()
  222. {
  223. set_needs_style_update(false);
  224. VERIFY(parent());
  225. auto new_specified_css_values = document().style_computer().compute_style(*this);
  226. if (m_specified_css_values && *m_specified_css_values == *new_specified_css_values)
  227. return;
  228. m_specified_css_values = move(new_specified_css_values);
  229. document().invalidate_layout();
  230. }
  231. NonnullRefPtr<CSS::StyleProperties> Element::computed_style()
  232. {
  233. auto element_computed_style = CSS::ResolvedCSSStyleDeclaration::create(*this);
  234. auto properties = CSS::StyleProperties::create();
  235. for (auto i = to_underlying(CSS::first_property_id); i <= to_underlying(CSS::last_property_id); ++i) {
  236. auto property_id = (CSS::PropertyID)i;
  237. auto maybe_value = element_computed_style->property(property_id);
  238. if (!maybe_value.has_value())
  239. continue;
  240. properties->set_property(property_id, maybe_value.release_value().value);
  241. }
  242. return properties;
  243. }
  244. RefPtr<DOMTokenList> const& Element::class_list()
  245. {
  246. if (!m_class_list)
  247. m_class_list = DOMTokenList::create(*this, HTML::AttributeNames::class_);
  248. return m_class_list;
  249. }
  250. // https://dom.spec.whatwg.org/#dom-element-matches
  251. DOM::ExceptionOr<bool> Element::matches(StringView selectors) const
  252. {
  253. auto maybe_selectors = parse_selector(CSS::ParsingContext(static_cast<ParentNode&>(const_cast<Element&>(*this))), selectors);
  254. if (!maybe_selectors.has_value())
  255. return DOM::SyntaxError::create("Failed to parse selector");
  256. auto sel = maybe_selectors.value();
  257. for (auto& s : sel) {
  258. if (SelectorEngine::matches(s, *this))
  259. return true;
  260. }
  261. return false;
  262. }
  263. // https://dom.spec.whatwg.org/#dom-element-closest
  264. DOM::ExceptionOr<DOM::Element const*> Element::closest(StringView selectors) const
  265. {
  266. auto maybe_selectors = parse_selector(CSS::ParsingContext(static_cast<ParentNode&>(const_cast<Element&>(*this))), selectors);
  267. if (!maybe_selectors.has_value())
  268. return DOM::SyntaxError::create("Failed to parse selector");
  269. auto matches_selectors = [](CSS::SelectorList const& selector_list, Element const* element) {
  270. for (auto& selector : selector_list) {
  271. if (!SelectorEngine::matches(selector, *element))
  272. return false;
  273. }
  274. return true;
  275. };
  276. auto const selector_list = maybe_selectors.release_value();
  277. for (auto* element = this; element; element = element->parent_element()) {
  278. if (!matches_selectors(selector_list, element))
  279. continue;
  280. return element;
  281. }
  282. return nullptr;
  283. }
  284. ExceptionOr<void> Element::set_inner_html(String const& markup)
  285. {
  286. auto result = DOMParsing::inner_html_setter(*this, markup);
  287. if (result.is_exception())
  288. return result.exception();
  289. set_needs_style_update(true);
  290. return {};
  291. }
  292. // https://w3c.github.io/DOM-Parsing/#dom-innerhtml-innerhtml
  293. String Element::inner_html() const
  294. {
  295. return serialize_fragment(/* FIXME: Providing true for the require well-formed flag (which may throw) */);
  296. }
  297. bool Element::is_focused() const
  298. {
  299. return document().focused_element() == this;
  300. }
  301. bool Element::is_active() const
  302. {
  303. return document().active_element() == this;
  304. }
  305. NonnullRefPtr<HTMLCollection> Element::get_elements_by_class_name(FlyString const& class_name)
  306. {
  307. return HTMLCollection::create(*this, [class_name, quirks_mode = document().in_quirks_mode()](Element const& element) {
  308. return element.has_class(class_name, quirks_mode ? CaseSensitivity::CaseInsensitive : CaseSensitivity::CaseSensitive);
  309. });
  310. }
  311. void Element::set_shadow_root(RefPtr<ShadowRoot> shadow_root)
  312. {
  313. if (m_shadow_root == shadow_root)
  314. return;
  315. m_shadow_root = move(shadow_root);
  316. m_shadow_root->set_host(*this);
  317. invalidate_style();
  318. }
  319. NonnullRefPtr<CSS::CSSStyleDeclaration> Element::style_for_bindings()
  320. {
  321. if (!m_inline_style)
  322. m_inline_style = CSS::ElementInlineCSSStyleDeclaration::create(*this);
  323. return *m_inline_style;
  324. }
  325. // https://dom.spec.whatwg.org/#element-html-uppercased-qualified-name
  326. void Element::make_html_uppercased_qualified_name()
  327. {
  328. // This is allowed by the spec: "User agents could optimize qualified name and HTML-uppercased qualified name by storing them in internal slots."
  329. if (namespace_() == Namespace::HTML /* FIXME: and its node document is an HTML document */)
  330. m_html_uppercased_qualified_name = qualified_name().to_uppercase();
  331. else
  332. m_html_uppercased_qualified_name = qualified_name();
  333. }
  334. // https://html.spec.whatwg.org/multipage/webappapis.html#queue-an-element-task
  335. void Element::queue_an_element_task(HTML::Task::Source source, Function<void()> steps)
  336. {
  337. auto task = HTML::Task::create(source, &document(), [strong_this = NonnullRefPtr(*this), steps = move(steps)] {
  338. steps();
  339. });
  340. HTML::main_thread_event_loop().task_queue().add(move(task));
  341. }
  342. // https://html.spec.whatwg.org/multipage/syntax.html#void-elements
  343. bool Element::is_void_element() const
  344. {
  345. return local_name().is_one_of(HTML::TagNames::area, HTML::TagNames::base, HTML::TagNames::br, HTML::TagNames::col, HTML::TagNames::embed, HTML::TagNames::hr, HTML::TagNames::img, HTML::TagNames::input, HTML::TagNames::link, HTML::TagNames::meta, HTML::TagNames::param, HTML::TagNames::source, HTML::TagNames::track, HTML::TagNames::wbr);
  346. }
  347. // https://html.spec.whatwg.org/multipage/parsing.html#serializes-as-void
  348. bool Element::serializes_as_void() const
  349. {
  350. return is_void_element() || local_name().is_one_of(HTML::TagNames::basefont, HTML::TagNames::bgsound, HTML::TagNames::frame, HTML::TagNames::keygen);
  351. }
  352. // https://drafts.csswg.org/cssom-view/#dom-element-getboundingclientrect
  353. NonnullRefPtr<Geometry::DOMRect> Element::get_bounding_client_rect() const
  354. {
  355. // FIXME: Support inline layout nodes as well.
  356. auto* paint_box = this->paint_box();
  357. if (!paint_box)
  358. return Geometry::DOMRect::create(0, 0, 0, 0);
  359. VERIFY(document().browsing_context());
  360. auto viewport_offset = document().browsing_context()->viewport_scroll_offset();
  361. return Geometry::DOMRect::create(paint_box->absolute_rect().translated(-viewport_offset.x(), -viewport_offset.y()));
  362. }
  363. // https://drafts.csswg.org/cssom-view/#dom-element-getclientrects
  364. NonnullRefPtr<Geometry::DOMRectList> Element::get_client_rects() const
  365. {
  366. NonnullRefPtrVector<Geometry::DOMRect> rects;
  367. // 1. If the element on which it was invoked does not have an associated layout box return an empty DOMRectList object and stop this algorithm.
  368. if (!layout_node() || !layout_node()->is_box())
  369. return Geometry::DOMRectList::create(move(rects));
  370. // FIXME: 2. If the element has an associated SVG layout box return a DOMRectList object containing a single DOMRect object that describes
  371. // the bounding box of the element as defined by the SVG specification, applying the transforms that apply to the element and its ancestors.
  372. // FIXME: 3. Return a DOMRectList object containing DOMRect objects in content order, one for each box fragment,
  373. // describing its border area (including those with a height or width of zero) with the following constraints:
  374. // - Apply the transforms that apply to the element and its ancestors.
  375. // - If the element on which the method was invoked has a computed value for the display property of table
  376. // or inline-table include both the table box and the caption box, if any, but not the anonymous container box.
  377. // - Replace each anonymous block box with its child box(es) and repeat this until no anonymous block boxes are left in the final list.
  378. auto bounding_rect = get_bounding_client_rect();
  379. rects.append(bounding_rect);
  380. return Geometry::DOMRectList::create(move(rects));
  381. }
  382. int Element::client_top() const
  383. {
  384. if (auto* paint_box = this->paint_box())
  385. return paint_box->absolute_rect().top();
  386. return 0;
  387. }
  388. int Element::client_left() const
  389. {
  390. if (auto* paint_box = this->paint_box())
  391. return paint_box->absolute_rect().left();
  392. return 0;
  393. }
  394. int Element::client_width() const
  395. {
  396. if (auto* paint_box = this->paint_box())
  397. return paint_box->absolute_rect().width();
  398. return 0;
  399. }
  400. int Element::client_height() const
  401. {
  402. if (auto* paint_box = this->paint_box())
  403. return paint_box->absolute_rect().height();
  404. return 0;
  405. }
  406. void Element::children_changed()
  407. {
  408. Node::children_changed();
  409. set_needs_style_update(true);
  410. }
  411. void Element::set_pseudo_element_node(Badge<Layout::TreeBuilder>, CSS::Selector::PseudoElement pseudo_element, RefPtr<Layout::Node> pseudo_element_node)
  412. {
  413. m_pseudo_element_nodes[to_underlying(pseudo_element)] = move(pseudo_element_node);
  414. }
  415. RefPtr<Layout::Node> Element::get_pseudo_element_node(CSS::Selector::PseudoElement pseudo_element) const
  416. {
  417. return m_pseudo_element_nodes[to_underlying(pseudo_element)];
  418. }
  419. void Element::clear_pseudo_element_nodes(Badge<Layout::TreeBuilder>)
  420. {
  421. m_pseudo_element_nodes.fill(nullptr);
  422. }
  423. void Element::serialize_pseudo_elements_as_json(JsonArraySerializer<StringBuilder>& children_array) const
  424. {
  425. for (size_t i = 0; i < m_pseudo_element_nodes.size(); ++i) {
  426. auto& pseudo_element_node = m_pseudo_element_nodes[i];
  427. if (!pseudo_element_node)
  428. continue;
  429. auto object = MUST(children_array.add_object());
  430. MUST(object.add("name", String::formatted("::{}", CSS::pseudo_element_name(static_cast<CSS::Selector::PseudoElement>(i)))));
  431. MUST(object.add("type", "pseudo-element"));
  432. MUST(object.add("parent-id", id()));
  433. MUST(object.add("pseudo-element", i));
  434. MUST(object.finish());
  435. }
  436. }
  437. }