Element.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/AnyOf.h>
  7. #include <AK/StringBuilder.h>
  8. #include <LibWeb/CSS/Parser/Parser.h>
  9. #include <LibWeb/CSS/PropertyID.h>
  10. #include <LibWeb/CSS/ResolvedCSSStyleDeclaration.h>
  11. #include <LibWeb/CSS/SelectorEngine.h>
  12. #include <LibWeb/DOM/DOMException.h>
  13. #include <LibWeb/DOM/DOMTokenList.h>
  14. #include <LibWeb/DOM/Document.h>
  15. #include <LibWeb/DOM/Element.h>
  16. #include <LibWeb/DOM/ExceptionOr.h>
  17. #include <LibWeb/DOM/HTMLCollection.h>
  18. #include <LibWeb/DOM/ShadowRoot.h>
  19. #include <LibWeb/DOM/Text.h>
  20. #include <LibWeb/DOMParsing/InnerHTML.h>
  21. #include <LibWeb/Geometry/DOMRect.h>
  22. #include <LibWeb/HTML/BrowsingContext.h>
  23. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  24. #include <LibWeb/HTML/Parser/HTMLParser.h>
  25. #include <LibWeb/Layout/BlockContainer.h>
  26. #include <LibWeb/Layout/InlineNode.h>
  27. #include <LibWeb/Layout/ListItemBox.h>
  28. #include <LibWeb/Layout/TableBox.h>
  29. #include <LibWeb/Layout/TableCellBox.h>
  30. #include <LibWeb/Layout/TableRowBox.h>
  31. #include <LibWeb/Layout/TableRowGroupBox.h>
  32. #include <LibWeb/Layout/TreeBuilder.h>
  33. #include <LibWeb/Namespace.h>
  34. namespace Web::DOM {
  35. Element::Element(Document& document, QualifiedName qualified_name)
  36. : ParentNode(document, NodeType::ELEMENT_NODE)
  37. , m_qualified_name(move(qualified_name))
  38. , m_attributes(NamedNodeMap::create(*this))
  39. {
  40. make_html_uppercased_qualified_name();
  41. }
  42. Element::~Element()
  43. {
  44. }
  45. // https://dom.spec.whatwg.org/#dom-element-getattribute
  46. String Element::get_attribute(const FlyString& name) const
  47. {
  48. // 1. Let attr be the result of getting an attribute given qualifiedName and this.
  49. auto const* attribute = m_attributes->get_attribute(name);
  50. // 2. If attr is null, return null.
  51. if (!attribute)
  52. return {};
  53. // 3. Return attr’s value.
  54. return attribute->value();
  55. }
  56. // https://dom.spec.whatwg.org/#dom-element-setattribute
  57. ExceptionOr<void> Element::set_attribute(const FlyString& name, const String& value)
  58. {
  59. // 1. If qualifiedName does not match the Name production in XML, then throw an "InvalidCharacterError" DOMException.
  60. // FIXME: Proper name validation
  61. if (name.is_empty())
  62. return InvalidCharacterError::create("Attribute name must not be empty");
  63. // 2. If this is in the HTML namespace and its node document is an HTML document, then set qualifiedName to qualifiedName in ASCII lowercase.
  64. // FIXME: Handle the second condition, assume it is an HTML document for now.
  65. bool insert_as_lowercase = namespace_uri() == Namespace::HTML;
  66. // 3. Let attribute be the first attribute in this’s attribute list whose qualified name is qualifiedName, and null otherwise.
  67. auto* attribute = m_attributes->get_attribute(name);
  68. // 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.
  69. if (!attribute) {
  70. auto new_attribute = Attribute::create(document(), insert_as_lowercase ? name.to_lowercase() : name, value);
  71. m_attributes->append_attribute(new_attribute);
  72. attribute = new_attribute.ptr();
  73. }
  74. // 5. Change attribute to value.
  75. else {
  76. attribute->set_value(value);
  77. }
  78. parse_attribute(attribute->local_name(), value);
  79. // FIXME: Invalidate less.
  80. document().invalidate_style();
  81. return {};
  82. }
  83. // https://dom.spec.whatwg.org/#dom-element-removeattribute
  84. void Element::remove_attribute(const FlyString& name)
  85. {
  86. m_attributes->remove_attribute(name);
  87. // FIXME: Invalidate less.
  88. document().invalidate_style();
  89. }
  90. // https://dom.spec.whatwg.org/#dom-element-hasattribute
  91. bool Element::has_attribute(const FlyString& name) const
  92. {
  93. return m_attributes->get_attribute(name) != nullptr;
  94. }
  95. // https://dom.spec.whatwg.org/#dom-element-getattributenames
  96. Vector<String> Element::get_attribute_names() const
  97. {
  98. // The getAttributeNames() method steps are to return the qualified names of the attributes in this’s attribute list, in order; otherwise a new list.
  99. Vector<String> names;
  100. for (size_t i = 0; i < m_attributes->length(); ++i) {
  101. auto const* attribute = m_attributes->item(i);
  102. names.append(attribute->name());
  103. }
  104. return names;
  105. }
  106. bool Element::has_class(const FlyString& class_name, CaseSensitivity case_sensitivity) const
  107. {
  108. return any_of(m_classes, [&](auto& it) {
  109. return case_sensitivity == CaseSensitivity::CaseSensitive
  110. ? it == class_name
  111. : it.equals_ignoring_case(class_name);
  112. });
  113. }
  114. RefPtr<Layout::Node> Element::create_layout_node(NonnullRefPtr<CSS::StyleProperties> style)
  115. {
  116. auto display = style->display();
  117. if (local_name() == "noscript" && document().is_scripting_enabled())
  118. return nullptr;
  119. if (display.is_table_inside())
  120. return adopt_ref(*new Layout::TableBox(document(), this, move(style)));
  121. if (display.is_list_item())
  122. return adopt_ref(*new Layout::ListItemBox(document(), *this, move(style)));
  123. if (display.is_table_row())
  124. return adopt_ref(*new Layout::TableRowBox(document(), this, move(style)));
  125. if (display.is_table_cell())
  126. return adopt_ref(*new Layout::TableCellBox(document(), this, move(style)));
  127. if (display.is_table_row_group() || display.is_table_header_group() || display.is_table_footer_group())
  128. return adopt_ref(*new Layout::TableRowGroupBox(document(), *this, move(style)));
  129. if (display.is_table_column() || display.is_table_column_group() || display.is_table_caption()) {
  130. // FIXME: This is just an incorrect placeholder until we improve table layout support.
  131. return adopt_ref(*new Layout::BlockContainer(document(), this, move(style)));
  132. }
  133. if (display.is_inline_outside()) {
  134. if (display.is_flow_root_inside()) {
  135. auto block = adopt_ref(*new Layout::BlockContainer(document(), this, move(style)));
  136. block->set_inline(true);
  137. return block;
  138. }
  139. if (display.is_flow_inside())
  140. return adopt_ref(*new Layout::InlineNode(document(), *this, move(style)));
  141. TODO();
  142. }
  143. if (display.is_flow_inside() || display.is_flow_root_inside() || display.is_flex_inside())
  144. return adopt_ref(*new Layout::BlockContainer(document(), this, move(style)));
  145. TODO();
  146. }
  147. void Element::parse_attribute(const FlyString& name, const String& value)
  148. {
  149. if (name == HTML::AttributeNames::class_) {
  150. auto new_classes = value.split_view(' ');
  151. m_classes.clear();
  152. m_classes.ensure_capacity(new_classes.size());
  153. for (auto& new_class : new_classes) {
  154. m_classes.unchecked_append(new_class);
  155. }
  156. if (m_class_list)
  157. m_class_list->associated_attribute_changed(value);
  158. } else if (name == HTML::AttributeNames::style) {
  159. auto parsed_style = parse_css_declaration(CSS::ParsingContext(document()), value);
  160. if (!parsed_style.is_null()) {
  161. m_inline_style = CSS::ElementInlineCSSStyleDeclaration::create_and_take_properties_from(*this, parsed_style.release_nonnull());
  162. set_needs_style_update(true);
  163. }
  164. }
  165. }
  166. enum class StyleDifference {
  167. None,
  168. NeedsRepaint,
  169. NeedsRelayout,
  170. };
  171. static StyleDifference compute_style_difference(CSS::StyleProperties const& old_style, CSS::StyleProperties const& new_style, Layout::NodeWithStyle const& node)
  172. {
  173. if (old_style == new_style)
  174. return StyleDifference::None;
  175. bool needs_repaint = false;
  176. bool needs_relayout = false;
  177. if (new_style.display() != old_style.display())
  178. needs_relayout = true;
  179. if (new_style.color_or_fallback(CSS::PropertyID::Color, node, Color::Black) != old_style.color_or_fallback(CSS::PropertyID::Color, node, Color::Black))
  180. needs_repaint = true;
  181. else if (new_style.color_or_fallback(CSS::PropertyID::BackgroundColor, node, Color::Black) != old_style.color_or_fallback(CSS::PropertyID::BackgroundColor, node, Color::Black))
  182. needs_repaint = true;
  183. if (needs_relayout)
  184. return StyleDifference::NeedsRelayout;
  185. if (needs_repaint)
  186. return StyleDifference::NeedsRepaint;
  187. return StyleDifference::None;
  188. }
  189. void Element::recompute_style()
  190. {
  191. set_needs_style_update(false);
  192. VERIFY(parent());
  193. auto old_specified_css_values = m_specified_css_values;
  194. auto new_specified_css_values = document().style_computer().compute_style(*this);
  195. m_specified_css_values = new_specified_css_values;
  196. if (!layout_node()) {
  197. if (new_specified_css_values->display().is_none())
  198. return;
  199. // We need a new layout tree here!
  200. Layout::TreeBuilder tree_builder;
  201. (void)tree_builder.build(*this);
  202. return;
  203. }
  204. auto diff = StyleDifference::NeedsRelayout;
  205. if (old_specified_css_values && layout_node())
  206. diff = compute_style_difference(*old_specified_css_values, *new_specified_css_values, *layout_node());
  207. if (diff == StyleDifference::None)
  208. return;
  209. layout_node()->apply_style(*new_specified_css_values);
  210. if (diff == StyleDifference::NeedsRelayout) {
  211. document().set_needs_layout();
  212. return;
  213. }
  214. if (diff == StyleDifference::NeedsRepaint) {
  215. layout_node()->set_needs_display();
  216. }
  217. }
  218. NonnullRefPtr<CSS::StyleProperties> Element::computed_style()
  219. {
  220. auto element_computed_style = CSS::ResolvedCSSStyleDeclaration::create(*this);
  221. auto properties = CSS::StyleProperties::create();
  222. for (auto i = to_underlying(CSS::first_property_id); i <= to_underlying(CSS::last_property_id); ++i) {
  223. auto property_id = (CSS::PropertyID)i;
  224. auto maybe_value = element_computed_style->property(property_id);
  225. if (!maybe_value.has_value())
  226. continue;
  227. properties->set_property(property_id, maybe_value.release_value().value);
  228. }
  229. return properties;
  230. }
  231. RefPtr<DOMTokenList> const& Element::class_list()
  232. {
  233. if (!m_class_list)
  234. m_class_list = DOMTokenList::create(*this, HTML::AttributeNames::class_);
  235. return m_class_list;
  236. }
  237. // https://dom.spec.whatwg.org/#dom-element-matches
  238. DOM::ExceptionOr<bool> Element::matches(StringView selectors) const
  239. {
  240. auto maybe_selectors = parse_selector(CSS::ParsingContext(static_cast<ParentNode&>(const_cast<Element&>(*this))), selectors);
  241. if (!maybe_selectors.has_value())
  242. return DOM::SyntaxError::create("Failed to parse selector");
  243. auto sel = maybe_selectors.value();
  244. for (auto& s : sel) {
  245. if (SelectorEngine::matches(s, *this))
  246. return true;
  247. }
  248. return false;
  249. }
  250. ExceptionOr<void> Element::set_inner_html(String const& markup)
  251. {
  252. auto result = DOMParsing::inner_html_setter(*this, markup);
  253. if (result.is_exception())
  254. return result.exception();
  255. set_needs_style_update(true);
  256. return {};
  257. }
  258. // https://w3c.github.io/DOM-Parsing/#dom-innerhtml-innerhtml
  259. String Element::inner_html() const
  260. {
  261. return serialize_fragment(/* FIXME: Providing true for the require well-formed flag (which may throw) */);
  262. }
  263. bool Element::is_focused() const
  264. {
  265. return document().focused_element() == this;
  266. }
  267. bool Element::is_active() const
  268. {
  269. return document().active_element() == this;
  270. }
  271. NonnullRefPtr<HTMLCollection> Element::get_elements_by_class_name(FlyString const& class_name)
  272. {
  273. return HTMLCollection::create(*this, [class_name, quirks_mode = document().in_quirks_mode()](Element const& element) {
  274. return element.has_class(class_name, quirks_mode ? CaseSensitivity::CaseInsensitive : CaseSensitivity::CaseSensitive);
  275. });
  276. }
  277. void Element::set_shadow_root(RefPtr<ShadowRoot> shadow_root)
  278. {
  279. if (m_shadow_root == shadow_root)
  280. return;
  281. m_shadow_root = move(shadow_root);
  282. invalidate_style();
  283. }
  284. NonnullRefPtr<CSS::CSSStyleDeclaration> Element::style_for_bindings()
  285. {
  286. if (!m_inline_style)
  287. m_inline_style = CSS::ElementInlineCSSStyleDeclaration::create(*this);
  288. return *m_inline_style;
  289. }
  290. // https://dom.spec.whatwg.org/#element-html-uppercased-qualified-name
  291. void Element::make_html_uppercased_qualified_name()
  292. {
  293. // This is allowed by the spec: "User agents could optimize qualified name and HTML-uppercased qualified name by storing them in internal slots."
  294. if (namespace_() == Namespace::HTML /* FIXME: and its node document is an HTML document */)
  295. m_html_uppercased_qualified_name = qualified_name().to_uppercase();
  296. else
  297. m_html_uppercased_qualified_name = qualified_name();
  298. }
  299. // https://html.spec.whatwg.org/multipage/webappapis.html#queue-an-element-task
  300. void Element::queue_an_element_task(HTML::Task::Source source, Function<void()> steps)
  301. {
  302. auto task = HTML::Task::create(source, &document(), [strong_this = NonnullRefPtr(*this), steps = move(steps)] {
  303. steps();
  304. });
  305. HTML::main_thread_event_loop().task_queue().add(move(task));
  306. }
  307. // https://html.spec.whatwg.org/multipage/syntax.html#void-elements
  308. bool Element::is_void_element() const
  309. {
  310. 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);
  311. }
  312. // https://html.spec.whatwg.org/multipage/parsing.html#serializes-as-void
  313. bool Element::serializes_as_void() const
  314. {
  315. return is_void_element() || local_name().is_one_of(HTML::TagNames::basefont, HTML::TagNames::bgsound, HTML::TagNames::frame, HTML::TagNames::keygen);
  316. }
  317. // https://drafts.csswg.org/cssom-view/#dom-element-getboundingclientrect
  318. NonnullRefPtr<Geometry::DOMRect> Element::get_bounding_client_rect() const
  319. {
  320. // FIXME: Support inline layout nodes as well.
  321. if (!layout_node() || !layout_node()->is_box())
  322. return Geometry::DOMRect::create(0, 0, 0, 0);
  323. VERIFY(document().browsing_context());
  324. auto viewport_offset = document().browsing_context()->viewport_scroll_offset();
  325. auto& box = static_cast<Layout::Box const&>(*layout_node());
  326. return Geometry::DOMRect::create(box.absolute_rect().translated(-viewport_offset.x(), -viewport_offset.y()));
  327. }
  328. int Element::client_top() const
  329. {
  330. if (!layout_node() || !layout_node()->is_box())
  331. return 0;
  332. auto& box = static_cast<Layout::Box const&>(*layout_node());
  333. return box.absolute_rect().top();
  334. }
  335. int Element::client_left() const
  336. {
  337. if (!layout_node() || !layout_node()->is_box())
  338. return 0;
  339. auto& box = static_cast<Layout::Box const&>(*layout_node());
  340. return box.absolute_rect().left();
  341. }
  342. int Element::client_width() const
  343. {
  344. if (!layout_node() || !layout_node()->is_box())
  345. return 0;
  346. auto& box = static_cast<Layout::Box const&>(*layout_node());
  347. return box.absolute_rect().width();
  348. }
  349. int Element::client_height() const
  350. {
  351. if (!layout_node() || !layout_node()->is_box())
  352. return 0;
  353. auto& box = static_cast<Layout::Box const&>(*layout_node());
  354. return box.absolute_rect().height();
  355. }
  356. void Element::children_changed()
  357. {
  358. Node::children_changed();
  359. set_needs_style_update(true);
  360. }
  361. }