Explorar el Código

LibHTML: Add Node::text_content()

This returns a String built from all of a Node's text descendants,
including itself.
Andreas Kling hace 5 años
padre
commit
0c6af2d5b4
Se han modificado 3 ficheros con 24 adiciones y 4 borrados
  1. 20 4
      Libraries/LibHTML/DOM/Node.cpp
  2. 2 0
      Libraries/LibHTML/DOM/Node.h
  3. 2 0
      Libraries/LibHTML/DOM/Text.h

+ 20 - 4
Libraries/LibHTML/DOM/Node.cpp

@@ -1,11 +1,12 @@
-#include <LibHTML/DOM/Node.h>
+#include <AK/StringBuilder.h>
+#include <LibHTML/CSS/StyleResolver.h>
 #include <LibHTML/DOM/Element.h>
 #include <LibHTML/DOM/HTMLAnchorElement.h>
-#include <LibHTML/CSS/StyleResolver.h>
-#include <LibHTML/Layout/LayoutNode.h>
+#include <LibHTML/DOM/Node.h>
 #include <LibHTML/Layout/LayoutBlock.h>
 #include <LibHTML/Layout/LayoutDocument.h>
 #include <LibHTML/Layout/LayoutInline.h>
+#include <LibHTML/Layout/LayoutNode.h>
 #include <LibHTML/Layout/LayoutText.h>
 
 Node::Node(Document& document, NodeType type)
@@ -39,7 +40,6 @@ RefPtr<LayoutNode> Node::create_layout_node(const StyleResolver& resolver, const
     ASSERT_NOT_REACHED();
 }
 
-
 RefPtr<LayoutNode> Node::create_layout_tree(const StyleResolver& resolver, const StyleProperties* parent_properties) const
 {
     auto layout_node = create_layout_node(resolver, parent_properties);
@@ -88,3 +88,19 @@ const HTMLElement* Node::enclosing_html_element() const
         return static_cast<const HTMLElement*>(this);
     return parent() ? parent()->enclosing_html_element() : nullptr;
 }
+
+String Node::text_content() const
+{
+    Vector<String> strings;
+    StringBuilder builder;
+    for (auto* child = first_child(); child; child = child->next_sibling()) {
+        auto text = child->text_content();
+        if (!text.is_empty()) {
+            builder.append(child->text_content());
+            builder.append(' ');
+        }
+    }
+    if (builder.length() > 1)
+        builder.trim(1);
+    return builder.to_string();
+}

+ 2 - 0
Libraries/LibHTML/DOM/Node.h

@@ -36,6 +36,8 @@ public:
 
     virtual String tag_name() const = 0;
 
+    virtual String text_content() const;
+
     Document& document() { return m_document; }
     const Document& document() const { return m_document; }
 

+ 2 - 0
Libraries/LibHTML/DOM/Text.h

@@ -12,6 +12,8 @@ public:
 
     virtual String tag_name() const override { return "#text"; }
 
+    virtual String text_content() const override { return m_data; }
+
 private:
     String m_data;
 };