Element.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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/CSSParser.h>
  29. #include <LibWeb/CSS/PropertyID.h>
  30. #include <LibWeb/CSS/StyleInvalidator.h>
  31. #include <LibWeb/CSS/StyleResolver.h>
  32. #include <LibWeb/DOM/Document.h>
  33. #include <LibWeb/DOM/Element.h>
  34. #include <LibWeb/DOM/ShadowRoot.h>
  35. #include <LibWeb/DOM/Text.h>
  36. #include <LibWeb/HTML/Parser/HTMLDocumentParser.h>
  37. #include <LibWeb/Layout/BlockBox.h>
  38. #include <LibWeb/Layout/InlineNode.h>
  39. #include <LibWeb/Layout/ListItemBox.h>
  40. #include <LibWeb/Layout/TableBox.h>
  41. #include <LibWeb/Layout/TableCellBox.h>
  42. #include <LibWeb/Layout/TableRowBox.h>
  43. #include <LibWeb/Layout/TableRowGroupBox.h>
  44. #include <LibWeb/Layout/TreeBuilder.h>
  45. #include <LibWeb/Namespace.h>
  46. namespace Web::DOM {
  47. Element::Element(Document& document, QualifiedName qualified_name)
  48. : ParentNode(document, NodeType::ELEMENT_NODE)
  49. , m_qualified_name(move(qualified_name))
  50. {
  51. }
  52. Element::~Element()
  53. {
  54. }
  55. Attribute* Element::find_attribute(const FlyString& name)
  56. {
  57. for (auto& attribute : m_attributes) {
  58. if (attribute.name() == name)
  59. return &attribute;
  60. }
  61. return nullptr;
  62. }
  63. const Attribute* Element::find_attribute(const FlyString& name) const
  64. {
  65. for (auto& attribute : m_attributes) {
  66. if (attribute.name() == name)
  67. return &attribute;
  68. }
  69. return nullptr;
  70. }
  71. String Element::attribute(const FlyString& name) const
  72. {
  73. if (auto* attribute = find_attribute(name))
  74. return attribute->value();
  75. return {};
  76. }
  77. void Element::set_attribute(const FlyString& name, const String& value)
  78. {
  79. CSS::StyleInvalidator style_invalidator(document());
  80. if (auto* attribute = find_attribute(name))
  81. attribute->set_value(value);
  82. else
  83. m_attributes.empend(name, value);
  84. parse_attribute(name, value);
  85. }
  86. void Element::remove_attribute(const FlyString& name)
  87. {
  88. CSS::StyleInvalidator style_invalidator(document());
  89. m_attributes.remove_first_matching([&](auto& attribute) { return attribute.name() == name; });
  90. }
  91. bool Element::has_class(const FlyString& class_name, CaseSensitivity case_sensitivity) const
  92. {
  93. return any_of(m_classes.begin(), m_classes.end(), [&](auto& it) {
  94. return case_sensitivity == CaseSensitivity::CaseSensitive
  95. ? it == class_name
  96. : it.to_lowercase() == class_name.to_lowercase();
  97. });
  98. }
  99. RefPtr<Layout::Node> Element::create_layout_node()
  100. {
  101. auto style = document().style_resolver().resolve_style(*this);
  102. const_cast<Element&>(*this).m_specified_css_values = style;
  103. auto display = style->display();
  104. if (display == CSS::Display::None)
  105. return nullptr;
  106. if (local_name() == "noscript" && document().is_scripting_enabled())
  107. return nullptr;
  108. switch (display) {
  109. case CSS::Display::None:
  110. ASSERT_NOT_REACHED();
  111. break;
  112. case CSS::Display::Block:
  113. return adopt(*new Layout::BlockBox(document(), this, move(style)));
  114. case CSS::Display::Inline:
  115. if (style->float_().value_or(CSS::Float::None) != CSS::Float::None)
  116. return adopt(*new Layout::BlockBox(document(), this, move(style)));
  117. return adopt(*new Layout::InlineNode(document(), *this, move(style)));
  118. case CSS::Display::ListItem:
  119. return adopt(*new Layout::ListItemBox(document(), *this, move(style)));
  120. case CSS::Display::Table:
  121. return adopt(*new Layout::TableBox(document(), this, move(style)));
  122. case CSS::Display::TableRow:
  123. return adopt(*new Layout::TableRowBox(document(), this, move(style)));
  124. case CSS::Display::TableCell:
  125. return adopt(*new Layout::TableCellBox(document(), this, move(style)));
  126. case CSS::Display::TableRowGroup:
  127. case CSS::Display::TableHeaderGroup:
  128. case CSS::Display::TableFooterGroup:
  129. return adopt(*new Layout::TableRowGroupBox(document(), *this, move(style)));
  130. case CSS::Display::InlineBlock: {
  131. auto inline_block = adopt(*new Layout::BlockBox(document(), this, move(style)));
  132. inline_block->set_inline(true);
  133. return inline_block;
  134. }
  135. case CSS::Display::Flex:
  136. return adopt(*new Layout::BlockBox(document(), this, move(style)));
  137. case CSS::Display::TableColumn:
  138. case CSS::Display::TableColumnGroup:
  139. case CSS::Display::TableCaption:
  140. // FIXME: This is just an incorrect placeholder until we improve table layout support.
  141. return adopt(*new Layout::BlockBox(document(), this, move(style)));
  142. }
  143. ASSERT_NOT_REACHED();
  144. }
  145. void Element::parse_attribute(const FlyString& name, const String& value)
  146. {
  147. if (name == HTML::AttributeNames::class_) {
  148. auto new_classes = value.split_view(' ');
  149. m_classes.clear();
  150. m_classes.ensure_capacity(new_classes.size());
  151. for (auto& new_class : new_classes) {
  152. m_classes.unchecked_append(new_class);
  153. }
  154. } else if (name == HTML::AttributeNames::style) {
  155. m_inline_style = parse_css_declaration(CSS::ParsingContext(document()), value);
  156. set_needs_style_update(true);
  157. }
  158. }
  159. enum class StyleDifference {
  160. None,
  161. NeedsRepaint,
  162. NeedsRelayout,
  163. };
  164. static StyleDifference compute_style_difference(const CSS::StyleProperties& old_style, const CSS::StyleProperties& new_style, const Document& document)
  165. {
  166. if (old_style == new_style)
  167. return StyleDifference::None;
  168. bool needs_repaint = false;
  169. bool needs_relayout = false;
  170. if (new_style.display() != old_style.display())
  171. needs_relayout = true;
  172. if (new_style.color_or_fallback(CSS::PropertyID::Color, document, Color::Black) != old_style.color_or_fallback(CSS::PropertyID::Color, document, Color::Black))
  173. needs_repaint = true;
  174. else if (new_style.color_or_fallback(CSS::PropertyID::BackgroundColor, document, Color::Black) != old_style.color_or_fallback(CSS::PropertyID::BackgroundColor, document, Color::Black))
  175. needs_repaint = true;
  176. if (needs_relayout)
  177. return StyleDifference::NeedsRelayout;
  178. if (needs_repaint)
  179. return StyleDifference::NeedsRepaint;
  180. return StyleDifference::None;
  181. }
  182. void Element::recompute_style()
  183. {
  184. set_needs_style_update(false);
  185. ASSERT(parent());
  186. auto old_specified_css_values = m_specified_css_values;
  187. auto new_specified_css_values = document().style_resolver().resolve_style(*this);
  188. m_specified_css_values = new_specified_css_values;
  189. if (!layout_node()) {
  190. if (new_specified_css_values->display() == CSS::Display::None)
  191. return;
  192. // We need a new layout tree here!
  193. Layout::TreeBuilder tree_builder;
  194. tree_builder.build(*this);
  195. return;
  196. }
  197. auto diff = StyleDifference::NeedsRelayout;
  198. if (old_specified_css_values)
  199. diff = compute_style_difference(*old_specified_css_values, *new_specified_css_values, document());
  200. if (diff == StyleDifference::None)
  201. return;
  202. layout_node()->apply_style(*new_specified_css_values);
  203. if (diff == StyleDifference::NeedsRelayout) {
  204. document().schedule_forced_layout();
  205. return;
  206. }
  207. if (diff == StyleDifference::NeedsRepaint) {
  208. layout_node()->set_needs_display();
  209. }
  210. }
  211. NonnullRefPtr<CSS::StyleProperties> Element::computed_style()
  212. {
  213. // FIXME: This implementation is not doing anything it's supposed to.
  214. auto properties = m_specified_css_values->clone();
  215. if (layout_node() && layout_node()->has_style()) {
  216. CSS::PropertyID box_model_metrics[] = {
  217. CSS::PropertyID::MarginTop,
  218. CSS::PropertyID::MarginBottom,
  219. CSS::PropertyID::MarginLeft,
  220. CSS::PropertyID::MarginRight,
  221. CSS::PropertyID::PaddingTop,
  222. CSS::PropertyID::PaddingBottom,
  223. CSS::PropertyID::PaddingLeft,
  224. CSS::PropertyID::PaddingRight,
  225. CSS::PropertyID::BorderTopWidth,
  226. CSS::PropertyID::BorderBottomWidth,
  227. CSS::PropertyID::BorderLeftWidth,
  228. CSS::PropertyID::BorderRightWidth,
  229. };
  230. for (CSS::PropertyID id : box_model_metrics) {
  231. auto prop = m_specified_css_values->property(id);
  232. if (prop.has_value())
  233. properties->set_property(id, prop.value());
  234. }
  235. }
  236. return properties;
  237. }
  238. void Element::set_inner_html(StringView markup)
  239. {
  240. auto new_children = HTML::HTMLDocumentParser::parse_html_fragment(*this, markup);
  241. remove_all_children();
  242. while (!new_children.is_empty()) {
  243. append_child(new_children.take_first());
  244. }
  245. set_needs_style_update(true);
  246. document().invalidate_layout();
  247. }
  248. String Element::inner_html() const
  249. {
  250. auto escape_string = [](const StringView& string, bool attribute_mode) -> String {
  251. // https://html.spec.whatwg.org/multipage/parsing.html#escapingString
  252. StringBuilder builder;
  253. for (auto& ch : string) {
  254. if (ch == '&')
  255. builder.append("&amp;");
  256. // FIXME: also replace U+00A0 NO-BREAK SPACE with &nbsp;
  257. else if (ch == '"' && attribute_mode)
  258. builder.append("&quot;");
  259. else if (ch == '<' && !attribute_mode)
  260. builder.append("&lt;");
  261. else if (ch == '>' && !attribute_mode)
  262. builder.append("&gt;");
  263. else
  264. builder.append(ch);
  265. }
  266. return builder.to_string();
  267. };
  268. StringBuilder builder;
  269. Function<void(const Node&)> recurse = [&](auto& node) {
  270. for (auto* child = node.first_child(); child; child = child->next_sibling()) {
  271. if (child->is_element()) {
  272. auto& element = downcast<Element>(*child);
  273. builder.append('<');
  274. builder.append(element.local_name());
  275. element.for_each_attribute([&](auto& name, auto& value) {
  276. builder.append(' ');
  277. builder.append(name);
  278. builder.append('=');
  279. builder.append('"');
  280. builder.append(escape_string(value, true));
  281. builder.append('"');
  282. });
  283. builder.append('>');
  284. recurse(*child);
  285. // FIXME: This should be skipped for void elements
  286. builder.append("</");
  287. builder.append(element.local_name());
  288. builder.append('>');
  289. }
  290. if (child->is_text()) {
  291. auto& text = downcast<Text>(*child);
  292. builder.append(escape_string(text.data(), false));
  293. }
  294. // FIXME: Also handle Comment, ProcessingInstruction, DocumentType
  295. }
  296. };
  297. recurse(*this);
  298. return builder.to_string();
  299. }
  300. bool Element::is_focused() const
  301. {
  302. return document().focused_element() == this;
  303. }
  304. NonnullRefPtrVector<Element> Element::get_elements_by_tag_name(const FlyString& tag_name) const
  305. {
  306. // FIXME: Support "*" for tag_name
  307. // https://dom.spec.whatwg.org/#concept-getelementsbytagname
  308. NonnullRefPtrVector<Element> elements;
  309. for_each_in_subtree_of_type<Element>([&](auto& element) {
  310. if (element.namespace_() == Namespace::HTML
  311. ? element.local_name().to_lowercase() == tag_name.to_lowercase()
  312. : element.local_name() == tag_name) {
  313. elements.append(element);
  314. }
  315. return IterationDecision::Continue;
  316. });
  317. return elements;
  318. }
  319. NonnullRefPtrVector<Element> Element::get_elements_by_class_name(const FlyString& class_name) const
  320. {
  321. NonnullRefPtrVector<Element> elements;
  322. for_each_in_subtree_of_type<Element>([&](auto& element) {
  323. if (element.has_class(class_name, m_document->in_quirks_mode() ? CaseSensitivity::CaseInsensitive : CaseSensitivity::CaseSensitive))
  324. elements.append(element);
  325. return IterationDecision::Continue;
  326. });
  327. return elements;
  328. }
  329. void Element::set_shadow_root(RefPtr<ShadowRoot> shadow_root)
  330. {
  331. if (m_shadow_root == shadow_root)
  332. return;
  333. m_shadow_root = move(shadow_root);
  334. invalidate_style();
  335. }
  336. }