@@ -2,7 +2,8 @@ use super::node::{Node, write_html_list};
22#[ cfg( feature = "source-span" ) ]
33use super :: span:: SourceSpan ;
44use crate :: dom:: vecmap:: VecMap ;
5- use crate :: { Attribute , VecSet } ;
5+ use crate :: { Attribute , Text , VecSet } ;
6+ use html_escape:: decode_html_entities;
67use ownable:: { IntoOwned , ToBorrowed , ToOwned } ;
78use serde:: Serialize ;
89use std:: borrow:: Cow ;
@@ -151,6 +152,39 @@ impl<'a> Element<'a> {
151152 writer. push ( '>' ) ;
152153 }
153154 }
155+
156+ /// Strip all tags.
157+ ///
158+ /// Note that html entities are not removed, only tags.
159+ /// Use [`Self::to_text`], or [`Text::decode`] on the result.
160+ pub fn strip_tags ( & self ) -> Text < ' _ > {
161+ if let & [ Node :: Text ( t) ] = & self . children . as_slice ( ) {
162+ t. to_borrowed ( )
163+ } else {
164+ let mut result = String :: new ( ) ;
165+ self . write_strip_tags ( & mut result) ;
166+ Text ( result. into ( ) )
167+ }
168+ }
169+
170+ fn write_strip_tags ( & self , writer : & mut String ) {
171+ for c in & self . children {
172+ match c {
173+ Node :: Text ( t) => writer. push_str ( t) ,
174+ Node :: Element ( e) => e. write_strip_tags ( writer) ,
175+ Node :: Comment ( _) => ( ) ,
176+ }
177+ }
178+ }
179+
180+ /// Strip tags and decode html-entities.
181+ pub fn to_text ( & self ) -> Cow < ' _ , str > {
182+ let t = self . strip_tags ( ) . 0 ;
183+ match decode_html_entities ( & t) {
184+ Cow :: Borrowed ( _) => t, // it's only returned as borrowed if the whole input is passed though
185+ Cow :: Owned ( o) => Cow :: Owned ( o) ,
186+ }
187+ }
154188}
155189
156190pub ( crate ) fn for_each_element < ' a , F > ( tree : & mut [ Node < ' a > ] , f : & mut F ) -> ControlFlow < ( ) , ( ) >
0 commit comments