Element.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/AnyOf.h>
  27. #include <AK/StringBuilder.h>
  28. #include <LibWeb/CSS/Parser/DeprecatedCSSParser.h>
  29. #include <LibWeb/CSS/PropertyID.h>
  30. #include <LibWeb/CSS/StyleInvalidator.h>
  31. #include <LibWeb/CSS/StyleResolver.h>
  32. #include <LibWeb/DOM/DOMException.h>
  33. #include <LibWeb/DOM/Document.h>
  34. #include <LibWeb/DOM/Element.h>
  35. #include <LibWeb/DOM/ExceptionOr.h>
  36. #include <LibWeb/DOM/ShadowRoot.h>
  37. #include <LibWeb/DOM/Text.h>
  38. #include <LibWeb/HTML/Parser/HTMLDocumentParser.h>
  39. #include <LibWeb/Layout/BlockBox.h>
  40. #include <LibWeb/Layout/InlineNode.h>
  41. #include <LibWeb/Layout/ListItemBox.h>
  42. #include <LibWeb/Layout/TableBox.h>
  43. #include <LibWeb/Layout/TableCellBox.h>
  44. #include <LibWeb/Layout/TableRowBox.h>
  45. #include <LibWeb/Layout/TableRowGroupBox.h>
  46. #include <LibWeb/Layout/TreeBuilder.h>
  47. #include <LibWeb/Namespace.h>
  48. namespace Web::DOM {
  49. Element::Element(Document& document, QualifiedName qualified_name)
  50. : ParentNode(document, NodeType::ELEMENT_NODE)
  51. , m_qualified_name(move(qualified_name))
  52. {
  53. }
  54. Element::~Element()
  55. {
  56. }
  57. Attribute* Element::find_attribute(const FlyString& name)
  58. {
  59. for (auto& attribute : m_attributes) {
  60. if (attribute.name() == name)
  61. return &attribute;
  62. }
  63. return nullptr;
  64. }
  65. const Attribute* Element::find_attribute(const FlyString& name) const
  66. {
  67. for (auto& attribute : m_attributes) {
  68. if (attribute.name() == name)
  69. return &attribute;
  70. }
  71. return nullptr;
  72. }
  73. String Element::attribute(const FlyString& name) const
  74. {
  75. if (auto* attribute = find_attribute(name))
  76. return attribute->value();
  77. return {};
  78. }
  79. ExceptionOr<void> Element::set_attribute(const FlyString& name, const String& value)
  80. {
  81. // FIXME: Proper name validation
  82. if (name.is_empty())
  83. return InvalidCharacterError::create("Attribute name must not be empty");
  84. CSS::StyleInvalidator style_invalidator(document());
  85. if (auto* attribute = find_attribute(name))
  86. attribute->set_value(value);
  87. else
  88. m_attributes.empend(name, value);
  89. parse_attribute(name, value);
  90. return {};
  91. }
  92. void Element::remove_attribute(const FlyString& name)
  93. {
  94. CSS::StyleInvalidator style_invalidator(document());
  95. m_attributes.remove_first_matching([&](auto& attribute) { return attribute.name() == name; });
  96. }
  97. bool Element::has_class(const FlyString& class_name, CaseSensitivity case_sensitivity) const
  98. {
  99. return any_of(m_classes.begin(), m_classes.end(), [&](auto& it) {
  100. return case_sensitivity == CaseSensitivity::CaseSensitive
  101. ? it == class_name
  102. : it.to_lowercase() == class_name.to_lowercase();
  103. });
  104. }
  105. RefPtr<Layout::Node> Element::create_layout_node()
  106. {
  107. auto style = document().style_resolver().resolve_style(*this);
  108. const_cast<Element&>(*this).m_specified_css_values = style;
  109. auto display = style->display();
  110. if (display == CSS::Display::None)
  111. return nullptr;
  112. if (local_name() == "noscript" && document().is_scripting_enabled())
  113. return nullptr;
  114. switch (display) {
  115. case CSS::Display::None:
  116. VERIFY_NOT_REACHED();
  117. break;
  118. case CSS::Display::Block:
  119. return adopt(*new Layout::BlockBox(document(), this, move(style)));
  120. case CSS::Display::Inline:
  121. if (style->float_().value_or(CSS::Float::None) != CSS::Float::None)
  122. return adopt(*new Layout::BlockBox(document(), this, move(style)));
  123. return adopt(*new Layout::InlineNode(document(), *this, move(style)));
  124. case CSS::Display::ListItem:
  125. return adopt(*new Layout::ListItemBox(document(), *this, move(style)));
  126. case CSS::Display::Table:
  127. return adopt(*new Layout::TableBox(document(), this, move(style)));
  128. case CSS::Display::TableRow:
  129. return adopt(*new Layout::TableRowBox(document(), this, move(style)));
  130. case CSS::Display::TableCell:
  131. return adopt(*new Layout::TableCellBox(document(), this, move(style)));
  132. case CSS::Display::TableRowGroup:
  133. case CSS::Display::TableHeaderGroup:
  134. case CSS::Display::TableFooterGroup:
  135. return adopt(*new Layout::TableRowGroupBox(document(), *this, move(style)));
  136. case CSS::Display::InlineBlock: {
  137. auto inline_block = adopt(*new Layout::BlockBox(document(), this, move(style)));
  138. inline_block->set_inline(true);
  139. return inline_block;
  140. }
  141. case CSS::Display::Flex:
  142. return adopt(*new Layout::BlockBox(document(), this, move(style)));
  143. case CSS::Display::TableColumn:
  144. case CSS::Display::TableColumnGroup:
  145. case CSS::Display::TableCaption:
  146. // FIXME: This is just an incorrect placeholder until we improve table layout support.
  147. return adopt(*new Layout::BlockBox(document(), this, move(style)));
  148. }
  149. VERIFY_NOT_REACHED();
  150. }
  151. void Element::parse_attribute(const FlyString& name, const String& value)
  152. {
  153. if (name == HTML::AttributeNames::class_) {
  154. auto new_classes = value.split_view(' ');
  155. m_classes.clear();
  156. m_classes.ensure_capacity(new_classes.size());
  157. for (auto& new_class : new_classes) {
  158. m_classes.unchecked_append(new_class);
  159. }
  160. } else if (name == HTML::AttributeNames::style) {
  161. m_inline_style = parse_css_declaration(CSS::ParsingContext(document()), value);
  162. set_needs_style_update(true);
  163. }
  164. }
  165. enum class StyleDifference {
  166. None,
  167. NeedsRepaint,
  168. NeedsRelayout,
  169. };
  170. static StyleDifference compute_style_difference(const CSS::StyleProperties& old_style, const CSS::StyleProperties& new_style, const Document& document)
  171. {
  172. if (old_style == new_style)
  173. return StyleDifference::None;
  174. bool needs_repaint = false;
  175. bool needs_relayout = false;
  176. if (new_style.display() != old_style.display())
  177. needs_relayout = true;
  178. if (new_style.color_or_fallback(CSS::PropertyID::Color, document, Color::Black) != old_style.color_or_fallback(CSS::PropertyID::Color, document, Color::Black))
  179. needs_repaint = true;
  180. else if (new_style.color_or_fallback(CSS::PropertyID::BackgroundColor, document, Color::Black) != old_style.color_or_fallback(CSS::PropertyID::BackgroundColor, document, Color::Black))
  181. needs_repaint = true;
  182. if (needs_relayout)
  183. return StyleDifference::NeedsRelayout;
  184. if (needs_repaint)
  185. return StyleDifference::NeedsRepaint;
  186. return StyleDifference::None;
  187. }
  188. void Element::recompute_style()
  189. {
  190. set_needs_style_update(false);
  191. VERIFY(parent());
  192. auto old_specified_css_values = m_specified_css_values;
  193. auto new_specified_css_values = document().style_resolver().resolve_style(*this);
  194. m_specified_css_values = new_specified_css_values;
  195. if (!layout_node()) {
  196. if (new_specified_css_values->display() == CSS::Display::None)
  197. return;
  198. // We need a new layout tree here!
  199. Layout::TreeBuilder tree_builder;
  200. tree_builder.build(*this);
  201. return;
  202. }
  203. auto diff = StyleDifference::NeedsRelayout;
  204. if (old_specified_css_values)
  205. diff = compute_style_difference(*old_specified_css_values, *new_specified_css_values, document());
  206. if (diff == StyleDifference::None)
  207. return;
  208. layout_node()->apply_style(*new_specified_css_values);
  209. if (diff == StyleDifference::NeedsRelayout) {
  210. document().schedule_forced_layout();
  211. return;
  212. }
  213. if (diff == StyleDifference::NeedsRepaint) {
  214. layout_node()->set_needs_display();
  215. }
  216. }
  217. NonnullRefPtr<CSS::StyleProperties> Element::computed_style()
  218. {
  219. // FIXME: This implementation is not doing anything it's supposed to.
  220. auto properties = m_specified_css_values->clone();
  221. if (layout_node() && layout_node()->has_style()) {
  222. CSS::PropertyID box_model_metrics[] = {
  223. CSS::PropertyID::MarginTop,
  224. CSS::PropertyID::MarginBottom,
  225. CSS::PropertyID::MarginLeft,
  226. CSS::PropertyID::MarginRight,
  227. CSS::PropertyID::PaddingTop,
  228. CSS::PropertyID::PaddingBottom,
  229. CSS::PropertyID::PaddingLeft,
  230. CSS::PropertyID::PaddingRight,
  231. CSS::PropertyID::BorderTopWidth,
  232. CSS::PropertyID::BorderBottomWidth,
  233. CSS::PropertyID::BorderLeftWidth,
  234. CSS::PropertyID::BorderRightWidth,
  235. };
  236. for (CSS::PropertyID id : box_model_metrics) {
  237. auto prop = m_specified_css_values->property(id);
  238. if (prop.has_value())
  239. properties->set_property(id, prop.value());
  240. }
  241. }
  242. return properties;
  243. }
  244. void Element::set_inner_html(StringView markup)
  245. {
  246. auto new_children = HTML::HTMLDocumentParser::parse_html_fragment(*this, markup);
  247. remove_all_children();
  248. while (!new_children.is_empty()) {
  249. append_child(new_children.take_first());
  250. }
  251. set_needs_style_update(true);
  252. document().invalidate_layout();
  253. }
  254. String Element::inner_html() const
  255. {
  256. auto escape_string = [](const StringView& string, bool attribute_mode) -> String {
  257. // https://html.spec.whatwg.org/multipage/parsing.html#escapingString
  258. StringBuilder builder;
  259. for (auto& ch : string) {
  260. if (ch == '&')
  261. builder.append("&amp;");
  262. // FIXME: also replace U+00A0 NO-BREAK SPACE with &nbsp;
  263. else if (ch == '"' && attribute_mode)
  264. builder.append("&quot;");
  265. else if (ch == '<' && !attribute_mode)
  266. builder.append("&lt;");
  267. else if (ch == '>' && !attribute_mode)
  268. builder.append("&gt;");
  269. else
  270. builder.append(ch);
  271. }
  272. return builder.to_string();
  273. };
  274. StringBuilder builder;
  275. Function<void(const Node&)> recurse = [&](auto& node) {
  276. for (auto* child = node.first_child(); child; child = child->next_sibling()) {
  277. if (child->is_element()) {
  278. auto& element = downcast<Element>(*child);
  279. builder.append('<');
  280. builder.append(element.local_name());
  281. element.for_each_attribute([&](auto& name, auto& value) {
  282. builder.append(' ');
  283. builder.append(name);
  284. builder.append('=');
  285. builder.append('"');
  286. builder.append(escape_string(value, true));
  287. builder.append('"');
  288. });
  289. builder.append('>');
  290. recurse(*child);
  291. // FIXME: This should be skipped for void elements
  292. builder.append("</");
  293. builder.append(element.local_name());
  294. builder.append('>');
  295. }
  296. if (child->is_text()) {
  297. auto& text = downcast<Text>(*child);
  298. builder.append(escape_string(text.data(), false));
  299. }
  300. // FIXME: Also handle Comment, ProcessingInstruction, DocumentType
  301. }
  302. };
  303. recurse(*this);
  304. return builder.to_string();
  305. }
  306. bool Element::is_focused() const
  307. {
  308. return document().focused_element() == this;
  309. }
  310. NonnullRefPtrVector<Element> Element::get_elements_by_tag_name(const FlyString& tag_name) const
  311. {
  312. // FIXME: Support "*" for tag_name
  313. // https://dom.spec.whatwg.org/#concept-getelementsbytagname
  314. NonnullRefPtrVector<Element> elements;
  315. for_each_in_inclusive_subtree_of_type<Element>([&](auto& element) {
  316. if (element.namespace_() == Namespace::HTML
  317. ? element.local_name().to_lowercase() == tag_name.to_lowercase()
  318. : element.local_name() == tag_name) {
  319. elements.append(element);
  320. }
  321. return IterationDecision::Continue;
  322. });
  323. return elements;
  324. }
  325. NonnullRefPtrVector<Element> Element::get_elements_by_class_name(const FlyString& class_name) const
  326. {
  327. NonnullRefPtrVector<Element> elements;
  328. for_each_in_inclusive_subtree_of_type<Element>([&](auto& element) {
  329. if (element.has_class(class_name, m_document->in_quirks_mode() ? CaseSensitivity::CaseInsensitive : CaseSensitivity::CaseSensitive))
  330. elements.append(element);
  331. return IterationDecision::Continue;
  332. });
  333. return elements;
  334. }
  335. void Element::set_shadow_root(RefPtr<ShadowRoot> shadow_root)
  336. {
  337. if (m_shadow_root == shadow_root)
  338. return;
  339. m_shadow_root = move(shadow_root);
  340. invalidate_style();
  341. }
  342. NonnullRefPtr<CSS::CSSStyleDeclaration> Element::style_for_bindings()
  343. {
  344. if (!m_inline_style)
  345. m_inline_style = CSS::ElementInlineCSSStyleDeclaration::create(*this);
  346. return *m_inline_style;
  347. }
  348. }