Element.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. 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. void Element::set_attribute(const FlyString& name, const String& value)
  80. {
  81. CSS::StyleInvalidator style_invalidator(document());
  82. if (auto* attribute = find_attribute(name))
  83. attribute->set_value(value);
  84. else
  85. m_attributes.empend(name, value);
  86. parse_attribute(name, value);
  87. }
  88. void Element::remove_attribute(const FlyString& name)
  89. {
  90. CSS::StyleInvalidator style_invalidator(document());
  91. m_attributes.remove_first_matching([&](auto& attribute) { return attribute.name() == name; });
  92. }
  93. bool Element::has_class(const FlyString& class_name, CaseSensitivity case_sensitivity) const
  94. {
  95. return any_of(m_classes.begin(), m_classes.end(), [&](auto& it) {
  96. return case_sensitivity == CaseSensitivity::CaseSensitive
  97. ? it == class_name
  98. : it.to_lowercase() == class_name.to_lowercase();
  99. });
  100. }
  101. RefPtr<Layout::Node> Element::create_layout_node()
  102. {
  103. auto style = document().style_resolver().resolve_style(*this);
  104. const_cast<Element&>(*this).m_specified_css_values = style;
  105. auto display = style->display();
  106. if (display == CSS::Display::None)
  107. return nullptr;
  108. if (local_name() == "noscript" && document().is_scripting_enabled())
  109. return nullptr;
  110. switch (display) {
  111. case CSS::Display::None:
  112. ASSERT_NOT_REACHED();
  113. break;
  114. case CSS::Display::Block:
  115. return adopt(*new Layout::BlockBox(document(), this, move(style)));
  116. case CSS::Display::Inline:
  117. if (style->float_().value_or(CSS::Float::None) != CSS::Float::None)
  118. return adopt(*new Layout::BlockBox(document(), this, move(style)));
  119. return adopt(*new Layout::InlineNode(document(), *this, move(style)));
  120. case CSS::Display::ListItem:
  121. return adopt(*new Layout::ListItemBox(document(), *this, move(style)));
  122. case CSS::Display::Table:
  123. return adopt(*new Layout::TableBox(document(), this, move(style)));
  124. case CSS::Display::TableRow:
  125. return adopt(*new Layout::TableRowBox(document(), this, move(style)));
  126. case CSS::Display::TableCell:
  127. return adopt(*new Layout::TableCellBox(document(), this, move(style)));
  128. case CSS::Display::TableRowGroup:
  129. case CSS::Display::TableHeaderGroup:
  130. case CSS::Display::TableFooterGroup:
  131. return adopt(*new Layout::TableRowGroupBox(document(), *this, move(style)));
  132. case CSS::Display::InlineBlock: {
  133. auto inline_block = adopt(*new Layout::BlockBox(document(), this, move(style)));
  134. inline_block->set_inline(true);
  135. return inline_block;
  136. }
  137. case CSS::Display::Flex:
  138. return adopt(*new Layout::BlockBox(document(), this, move(style)));
  139. case CSS::Display::TableColumn:
  140. case CSS::Display::TableColumnGroup:
  141. case CSS::Display::TableCaption:
  142. // FIXME: This is just an incorrect placeholder until we improve table layout support.
  143. return adopt(*new Layout::BlockBox(document(), this, move(style)));
  144. }
  145. ASSERT_NOT_REACHED();
  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. } else if (name == HTML::AttributeNames::style) {
  157. m_inline_style = parse_css_declaration(CSS::ParsingContext(document()), value);
  158. set_needs_style_update(true);
  159. }
  160. }
  161. enum class StyleDifference {
  162. None,
  163. NeedsRepaint,
  164. NeedsRelayout,
  165. };
  166. static StyleDifference compute_style_difference(const CSS::StyleProperties& old_style, const CSS::StyleProperties& new_style, const Document& document)
  167. {
  168. if (old_style == new_style)
  169. return StyleDifference::None;
  170. bool needs_repaint = false;
  171. bool needs_relayout = false;
  172. if (new_style.display() != old_style.display())
  173. needs_relayout = true;
  174. if (new_style.color_or_fallback(CSS::PropertyID::Color, document, Color::Black) != old_style.color_or_fallback(CSS::PropertyID::Color, document, Color::Black))
  175. needs_repaint = true;
  176. else if (new_style.color_or_fallback(CSS::PropertyID::BackgroundColor, document, Color::Black) != old_style.color_or_fallback(CSS::PropertyID::BackgroundColor, document, Color::Black))
  177. needs_repaint = true;
  178. if (needs_relayout)
  179. return StyleDifference::NeedsRelayout;
  180. if (needs_repaint)
  181. return StyleDifference::NeedsRepaint;
  182. return StyleDifference::None;
  183. }
  184. void Element::recompute_style()
  185. {
  186. set_needs_style_update(false);
  187. ASSERT(parent());
  188. auto old_specified_css_values = m_specified_css_values;
  189. auto new_specified_css_values = document().style_resolver().resolve_style(*this);
  190. m_specified_css_values = new_specified_css_values;
  191. if (!layout_node()) {
  192. if (new_specified_css_values->display() == CSS::Display::None)
  193. return;
  194. // We need a new layout tree here!
  195. Layout::TreeBuilder tree_builder;
  196. tree_builder.build(*this);
  197. return;
  198. }
  199. // Don't bother with style on widgets. NATIVE LOOK & FEEL BABY!
  200. if (is<Layout::WidgetBox>(layout_node()))
  201. return;
  202. auto diff = StyleDifference::NeedsRelayout;
  203. if (old_specified_css_values)
  204. diff = compute_style_difference(*old_specified_css_values, *new_specified_css_values, document());
  205. if (diff == StyleDifference::None)
  206. return;
  207. layout_node()->apply_style(*new_specified_css_values);
  208. if (diff == StyleDifference::NeedsRelayout) {
  209. document().schedule_forced_layout();
  210. return;
  211. }
  212. if (diff == StyleDifference::NeedsRepaint) {
  213. layout_node()->set_needs_display();
  214. }
  215. }
  216. NonnullRefPtr<CSS::StyleProperties> Element::computed_style()
  217. {
  218. // FIXME: This implementation is not doing anything it's supposed to.
  219. auto properties = m_specified_css_values->clone();
  220. if (layout_node() && layout_node()->has_style()) {
  221. CSS::PropertyID box_model_metrics[] = {
  222. CSS::PropertyID::MarginTop,
  223. CSS::PropertyID::MarginBottom,
  224. CSS::PropertyID::MarginLeft,
  225. CSS::PropertyID::MarginRight,
  226. CSS::PropertyID::PaddingTop,
  227. CSS::PropertyID::PaddingBottom,
  228. CSS::PropertyID::PaddingLeft,
  229. CSS::PropertyID::PaddingRight,
  230. CSS::PropertyID::BorderTopWidth,
  231. CSS::PropertyID::BorderBottomWidth,
  232. CSS::PropertyID::BorderLeftWidth,
  233. CSS::PropertyID::BorderRightWidth,
  234. };
  235. for (CSS::PropertyID id : box_model_metrics) {
  236. auto prop = m_specified_css_values->property(id);
  237. if (prop.has_value())
  238. properties->set_property(id, prop.value());
  239. }
  240. }
  241. return properties;
  242. }
  243. void Element::set_inner_html(StringView markup)
  244. {
  245. auto new_children = HTML::HTMLDocumentParser::parse_html_fragment(*this, markup);
  246. remove_all_children();
  247. while (!new_children.is_empty()) {
  248. append_child(new_children.take_first());
  249. }
  250. set_needs_style_update(true);
  251. document().invalidate_layout();
  252. }
  253. String Element::inner_html() const
  254. {
  255. auto escape_string = [](const StringView& string, bool attribute_mode) -> String {
  256. // https://html.spec.whatwg.org/multipage/parsing.html#escapingString
  257. StringBuilder builder;
  258. for (auto& ch : string) {
  259. if (ch == '&')
  260. builder.append("&amp;");
  261. // FIXME: also replace U+00A0 NO-BREAK SPACE with &nbsp;
  262. else if (ch == '"' && attribute_mode)
  263. builder.append("&quot;");
  264. else if (ch == '<' && !attribute_mode)
  265. builder.append("&lt;");
  266. else if (ch == '>' && !attribute_mode)
  267. builder.append("&gt;");
  268. else
  269. builder.append(ch);
  270. }
  271. return builder.to_string();
  272. };
  273. StringBuilder builder;
  274. Function<void(const Node&)> recurse = [&](auto& node) {
  275. for (auto* child = node.first_child(); child; child = child->next_sibling()) {
  276. if (child->is_element()) {
  277. auto& element = downcast<Element>(*child);
  278. builder.append('<');
  279. builder.append(element.local_name());
  280. element.for_each_attribute([&](auto& name, auto& value) {
  281. builder.append(' ');
  282. builder.append(name);
  283. builder.append('=');
  284. builder.append('"');
  285. builder.append(escape_string(value, true));
  286. builder.append('"');
  287. });
  288. builder.append('>');
  289. recurse(*child);
  290. // FIXME: This should be skipped for void elements
  291. builder.append("</");
  292. builder.append(element.local_name());
  293. builder.append('>');
  294. }
  295. if (child->is_text()) {
  296. auto& text = downcast<Text>(*child);
  297. builder.append(escape_string(text.data(), false));
  298. }
  299. // FIXME: Also handle Comment, ProcessingInstruction, DocumentType
  300. }
  301. };
  302. recurse(*this);
  303. return builder.to_string();
  304. }
  305. bool Element::is_focused() const
  306. {
  307. return document().focused_element() == this;
  308. }
  309. }