Element.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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/Length.h>
  29. #include <LibWeb/CSS/Parser/CSSParser.h>
  30. #include <LibWeb/CSS/PropertyID.h>
  31. #include <LibWeb/CSS/StyleInvalidator.h>
  32. #include <LibWeb/CSS/StyleResolver.h>
  33. #include <LibWeb/DOM/Document.h>
  34. #include <LibWeb/DOM/DocumentFragment.h>
  35. #include <LibWeb/DOM/Element.h>
  36. #include <LibWeb/DOM/Text.h>
  37. #include <LibWeb/Dump.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/Layout/WidgetBox.h>
  48. #include <LibWeb/Namespace.h>
  49. namespace Web::DOM {
  50. Element::Element(Document& document, QualifiedName qualified_name)
  51. : ParentNode(document, NodeType::ELEMENT_NODE)
  52. , m_qualified_name(move(qualified_name))
  53. {
  54. }
  55. Element::~Element()
  56. {
  57. }
  58. Attribute* Element::find_attribute(const FlyString& name)
  59. {
  60. for (auto& attribute : m_attributes) {
  61. if (attribute.name() == name)
  62. return &attribute;
  63. }
  64. return nullptr;
  65. }
  66. const Attribute* Element::find_attribute(const FlyString& name) const
  67. {
  68. for (auto& attribute : m_attributes) {
  69. if (attribute.name() == name)
  70. return &attribute;
  71. }
  72. return nullptr;
  73. }
  74. String Element::attribute(const FlyString& name) const
  75. {
  76. if (auto* attribute = find_attribute(name))
  77. return attribute->value();
  78. return {};
  79. }
  80. void Element::set_attribute(const FlyString& name, const String& value)
  81. {
  82. CSS::StyleInvalidator style_invalidator(document());
  83. if (auto* attribute = find_attribute(name))
  84. attribute->set_value(value);
  85. else
  86. m_attributes.empend(name, value);
  87. parse_attribute(name, value);
  88. }
  89. void Element::remove_attribute(const FlyString& name)
  90. {
  91. CSS::StyleInvalidator style_invalidator(document());
  92. m_attributes.remove_first_matching([&](auto& attribute) { return attribute.name() == name; });
  93. }
  94. bool Element::has_class(const FlyString& class_name, CaseSensitivity case_sensitivity) const
  95. {
  96. return any_of(m_classes.begin(), m_classes.end(), [&](auto& it) {
  97. return case_sensitivity == CaseSensitivity::CaseSensitive
  98. ? it == class_name
  99. : it.to_lowercase() == class_name.to_lowercase();
  100. });
  101. }
  102. RefPtr<Layout::Node> Element::create_layout_node()
  103. {
  104. auto style = document().style_resolver().resolve_style(*this);
  105. const_cast<Element&>(*this).m_specified_css_values = style;
  106. auto display = style->display();
  107. if (display == CSS::Display::None)
  108. return nullptr;
  109. if (local_name() == "noscript" && document().is_scripting_enabled())
  110. return nullptr;
  111. switch (display) {
  112. case CSS::Display::None:
  113. ASSERT_NOT_REACHED();
  114. break;
  115. case CSS::Display::Block:
  116. return adopt(*new Layout::BlockBox(document(), this, move(style)));
  117. case CSS::Display::Inline:
  118. if (style->float_().value_or(CSS::Float::None) != CSS::Float::None)
  119. return adopt(*new Layout::BlockBox(document(), this, move(style)));
  120. return adopt(*new Layout::InlineNode(document(), *this, move(style)));
  121. case CSS::Display::ListItem:
  122. return adopt(*new Layout::ListItemBox(document(), *this, move(style)));
  123. case CSS::Display::Table:
  124. return adopt(*new Layout::TableBox(document(), this, move(style)));
  125. case CSS::Display::TableRow:
  126. return adopt(*new Layout::TableRowBox(document(), this, move(style)));
  127. case CSS::Display::TableCell:
  128. return adopt(*new Layout::TableCellBox(document(), this, move(style)));
  129. case CSS::Display::TableRowGroup:
  130. case CSS::Display::TableHeaderGroup:
  131. case CSS::Display::TableFooterGroup:
  132. return adopt(*new Layout::TableRowGroupBox(document(), *this, move(style)));
  133. case CSS::Display::InlineBlock: {
  134. auto inline_block = adopt(*new Layout::BlockBox(document(), this, move(style)));
  135. inline_block->set_inline(true);
  136. return inline_block;
  137. }
  138. case CSS::Display::Flex:
  139. return adopt(*new Layout::BlockBox(document(), this, move(style)));
  140. case CSS::Display::TableColumn:
  141. case CSS::Display::TableColumnGroup:
  142. case CSS::Display::TableCaption:
  143. // FIXME: This is just an incorrect placeholder until we improve table layout support.
  144. return adopt(*new Layout::BlockBox(document(), this, move(style)));
  145. }
  146. ASSERT_NOT_REACHED();
  147. }
  148. void Element::parse_attribute(const FlyString& name, const String& value)
  149. {
  150. if (name == HTML::AttributeNames::class_) {
  151. auto new_classes = value.split_view(' ');
  152. m_classes.clear();
  153. m_classes.ensure_capacity(new_classes.size());
  154. for (auto& new_class : new_classes) {
  155. m_classes.unchecked_append(new_class);
  156. }
  157. } else if (name == HTML::AttributeNames::style) {
  158. m_inline_style = parse_css_declaration(CSS::ParsingContext(document()), value);
  159. set_needs_style_update(true);
  160. }
  161. }
  162. enum class StyleDifference {
  163. None,
  164. NeedsRepaint,
  165. NeedsRelayout,
  166. };
  167. static StyleDifference compute_style_difference(const CSS::StyleProperties& old_style, const CSS::StyleProperties& new_style, const Document& document)
  168. {
  169. if (old_style == new_style)
  170. return StyleDifference::None;
  171. bool needs_repaint = false;
  172. bool needs_relayout = false;
  173. if (new_style.display() != old_style.display())
  174. needs_relayout = true;
  175. if (new_style.color_or_fallback(CSS::PropertyID::Color, document, Color::Black) != old_style.color_or_fallback(CSS::PropertyID::Color, document, Color::Black))
  176. needs_repaint = true;
  177. else if (new_style.color_or_fallback(CSS::PropertyID::BackgroundColor, document, Color::Black) != old_style.color_or_fallback(CSS::PropertyID::BackgroundColor, document, Color::Black))
  178. needs_repaint = true;
  179. if (needs_relayout)
  180. return StyleDifference::NeedsRelayout;
  181. if (needs_repaint)
  182. return StyleDifference::NeedsRepaint;
  183. return StyleDifference::None;
  184. }
  185. void Element::recompute_style()
  186. {
  187. set_needs_style_update(false);
  188. ASSERT(parent());
  189. auto old_specified_css_values = m_specified_css_values;
  190. auto new_specified_css_values = document().style_resolver().resolve_style(*this);
  191. m_specified_css_values = new_specified_css_values;
  192. if (!layout_node()) {
  193. if (new_specified_css_values->display() == CSS::Display::None)
  194. return;
  195. // We need a new layout tree here!
  196. Layout::TreeBuilder tree_builder;
  197. tree_builder.build(*this);
  198. return;
  199. }
  200. // Don't bother with style on widgets. NATIVE LOOK & FEEL BABY!
  201. if (is<Layout::WidgetBox>(layout_node()))
  202. return;
  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_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_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. }