Element.cpp 20 KB

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