Element.cpp 12 KB

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