blib/lib/String/Tagged/HTML.pm

filter: Statementstmt 92.9% 79 / 85 Branchbran 77.0% 37 / 48 Conditioncond 50.0% 1 / 2 MC/DCmcdc 0.0% 0 / 1 Subroutinesub 89.4% 17 / 19 Podpod 100% 4 / 4 totaltotal 86.7% 138 / 159 CC 31 SCAR 16.5
CC
31
Cov
87%
_cmp_tag_values
10.2
__ANON__
10.0
_escape_html
6.0
CRAP 5.2
↑ Summary
1 # You may distribute under the terms of either the GNU General Public License
2 # or the Artistic License (the same terms as Perl itself)
3 #
4 # (C) Paul Evans, 2011-2026 -- leonerd@leonerd.org.uk
5  
6 package String::Tagged::HTML 0.04;
7  
8 7 ▶use v5.20;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 7 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 7 ▶use feature qw( postderef signatures );
Subroutine BEGIN: called CC=1 SCAR=0.0
12 7 ▶no warnings qw( experimental::postderef experimental::signatures );
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 7 ▶use base qw( String::Tagged );
Subroutine BEGIN: called CC=1 SCAR=0.0
15 7 String::Tagged->VERSION( '0.20' );
16  
17 =head1 NAME
18  
19 C<String::Tagged::HTML> - handle HTML content using C<String::Tagged>
20  
21 =head1 SYNOPSIS
22  
23 =for highlighter language=perl
24  
25 use String::Tagged::HTML;
26  
27 my $st = String::Tagged::HTML->new( "An important message" );
28  
29 $st->apply_tag( 3, 9, b => 1 );
30  
31 print $st->as_html( "h1" );
32  
33 =head1 DESCRIPTION
34  
35 This subclass of L<String::Tagged> provides a method, C<as_html>, for rendering
36 the string as an HTML fragment, using the tags to provide formatting. For
37 example, the SYNOPSIS example will produce the output
38  
39 =for highlighter language=html
40  
41 <h1>An <b>important</b> message</h1>
42  
43 With the exception of tags named C<raw>, a tag applied to an extent of the
44 C<String::Tagged::HTML> will be rendered using start and end HTML tags of the
45 same name. If the tag's value is a C<HASH> reference, then this hash will be
46 used to provide additional attributes for the HTML element. Tags whose names
47 begin with C<_> will be ignored for this purpose.
48  
49 =for highlighter language=perl
50  
51 my $str = String::Tagged::HTML->new( "click " )
52 ->append_tagged( "here", a => { href => "/see/other.html" } );
53  
54 print $str->as_html( "p" );
55  
56 Z<>
57  
58 =for highlighter language=html
59  
60 <p>click <a href="/see/other.html">here</a></p>
61  
62 If it is not a C<HASH> reference, then its value ought to be a simple boolean
63 true value, such as C<1>.
64  
65 The special tag named C<raw> disables HTML entity escaping over its extent.
66  
67 =for highlighter language=perl
68  
69 my $str = String::Tagged::HTML->new( "This <content> is escaped" );
70  
71 my $br = String::Tagged::HTML->new_tagged( "<br/>", raw => 1 );
72  
73 print +( $str . $br )->as_html( "p" );
74  
75 Z<>
76  
77 =for highlighter language=html
78  
79 <p>This &lt;content&gt; is escaped<br/></p>
80  
81 =head2 Automatic C<< <span> >> Generation
82  
83 Tags whose names begin C<_span_style_...> are used to create a C<style>
84 attribute for an implied C<span> tag.
85  
86 All tags with this name prefix are collected together. The part of the name
87 following this prefix is used as the style property name and the value of the
88 tag used for its value. These are all joined into a single string, and that is
89 then used to generate the C<style> tag.
90  
91 As an extra convenience, any remaining underscores in the tag name will be
92 converted to hyphens in the style property name.
93  
94 =for highlighter language=perl
95  
96 my $str = String::Tagged::HTML->new( "Some big text" );
97 $str->apply_tag( 5, 3, _span_style_font_size => "large" );
98  
99 print $str->as_html
100  
101 Z<>
102  
103 =for highlighter language=html
104  
105 Some <span style="font-size: large;">big</span> text
106  
107 =head2 Tag Nesting
108  
109 Because of the arbitrary way that C<String::Tagged> tags may be applied, as
110 compared to the strict nesting requirements in HTML, the C<as_html> method may
111 have to break a single C<String::Tagged> tag into multiple regions. In the
112 following example, the C<i> tag has been split in two to allow it to overlap
113 correctly with C<b>.
114  
115 =for highlighter language=perl
116  
117 my $str = String::Tagged::HTML->new( "bbb b+i iii" );
118 $str->apply_tag( 0, 7, b => 1 );
119 $str->apply_tag( 4, 7, i => 1 );
120  
121 print $str->as_html
122  
123 Z<>
124  
125 =for highlighter language=html
126  
127 <b>bbb <i>b+i</i></b><i> iii</i>
128  
129 =head2 String::Tagged::Formatting SUPPORT
130  
131 L<String::Tagged::Formatting> specifes a standard way that subclasses of
132 C<String::Tagged> can express a variety of simple formatting styles. HTML is a
133 lot more flexible than this (and CSS doubly so). Certain limited support is
134 provided for converting C<String::Tagged::Formatting> tags into a form that
135 can be rendered into standalone HTML.
136  
137 The following tag conversions are supported:
138  
139 =for highlighter
140  
141 bold <strong>
142 under <u>
143 italic <em>
144 strike <strike>
145 monospace <tt>
146  
147 sizepos = "super" <sup>
148 sizepod = "sub" <sub>
149  
150 fg <span style="color: #rrggbb">
151 bg <span style="background-color: #rrggbb">
152  
153 link <a href="uri">
154  
155 =cut
156  
157 =head1 CONSTRUCTORS
158  
159 As well as the standard C<new> and C<new_tagged> constructors provided by
160 L<String::Tagged|String::Tagged/CONSTRUCTORS>, the following is provided.
161  
162 =cut
163  
164 =head2 new_raw
165  
166 =for highlighter language=perl
167  
168 $st = String::Tagged::HTML->new_raw( $str );
169  
170 Returns a new C<String::Tagged::HTML> instance with the C<raw> tag applied
171 over its entire length. This convenience is provided for creating objects
172 containing already-rendered HTML fragments.
173  
174 =cut
175  
176 10 ▶sub new_raw ( $class, $str )
Subroutine new_raw: called CC=1 SCAR=0.0
Pod documented
177 {
178 10 return $class->new_tagged( $str, raw => 1 );
179 }
180  
181 =head2 new_from_formatting
182  
183 $st = String::Tagged::HTML->new_from_formatting( $fmt, %params );
184  
185 Returns a new instance by converting L<String::Tagged::Formatting> standard
186 tags, as described above.
187  
188 The following additional named arguments are recognised:
189  
190 =over 4
191  
192 =item convert_linefeeds => BOOL
193  
194 Optional. If true, linefeeds in the source string will be converted into
195 C<< <br/> >> HTML tags in the result. Defaults to true if absent, but the
196 behaviour can be disabled by passing a defined-but-false value.
197  
198 =back
199  
200 =cut
201  
202 9 ▶sub new_from_formatting ( $class, $orig, %params )
Subroutine new_from_formatting: called CC=4 SCAR=14.9
Pod documented
203 {
204 my $ret = $class->clone( $orig,
205 only_tags => [qw( bold italic under strike monospace sizepos fg bg link )],
206 convert_tags => {
207 bold => "strong",
208 italic => "em",
209 under => "u",
210 # strike stands as is
211 monospace => "tt",
212 2 ▶ sizepos => sub ( $k, $v ) {
Subroutine __ANON__: called CC=3 SCAR=11.7
213 2 ▶ return "sup" => 1 if $v eq "super";
Branch: 1 branch
BranchTrueFalseTotal
if $v eq "super" 1 1 2
214 1 ▶ return "sub" => 1 if $v eq "sub";
Branch: 1 branch
BranchTrueFalseTotal
if $v eq "sub" 1 0 1
215 0 return;
216 },
217 0 ▶ fg => sub ( $k, $v ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
218 0 return _span_style_color => "#" . $v->as_rgb8->hex;
219 },
220 0 ▶ bg => sub ( $k, $v ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
221 0 return _span_style_background_color => "#" . $v->as_rgb8->hex;
222 },
223 1 ▶ link => sub ( $k, $v ) {
Subroutine __ANON__: called CC=2 SCAR=7.2
224 1 ▶ return unless defined( my $uri = $v->{uri} );
Branch: 1 branch
BranchTrueFalseTotal
unless defined(my $uri = $v->{"uri"}) 0 1 1
225 1 return a => { href => $uri };
226 },
227 }
228 9 );
229  
230 9 ▶ if( $params{convert_linefeeds} // 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params{"convert_linefeeds"} // 1) 9 0 9
Condition50%1/2
$params{"convert_linefeeds"} // 1
l!l
09
MC/DC0%0/1
$params{"convert_linefeeds"} // 1
$params{"convert_linefeeds"}
Truth table50%1/2
A
A= $params{"convert_linefeeds"}
Aresult
11
00
231 9 my $br_tag = $class->new_raw( "<br/>\n" );
232  
233 9 foreach my $e ( reverse $ret->match_extents( qr/\n/ ) ) {
234 1 $ret->set_substr( $e->start, $e->length, $br_tag );
235 }
236 }
237  
238 9 return $ret;
239 }
240  
241 =head2 parse_html
242  
243 $st = String::Tagged::HTML->parse_html( $html );
244  
245 Returns a new C<String::Tagged::HTML> instance by parsing the given HTML
246 content and composing the plaintext parts of the content, with tags applied
247 over the appropriate ranges of it.
248  
249 This parsing is currently performed using L<HTML::TreeBuilder>, and will not
250 work if that module is not available.
251  
252 =cut
253  
254 2 ▶sub parse_html ( $class, $content )
Subroutine parse_html: called CC=1 SCAR=0.0
Pod documented
255 {
256 2 require HTML::TreeBuilder;
257  
258 2 my $tree = HTML::TreeBuilder->new_from_content( $content );
259 2 my $body = $tree->find_by_tag_name( 'body' );
260  
261 2 return _traverse_html( $class, $body );
262 }
263  
264 9 ▶sub _traverse_html ( $class, $node )
Subroutine _traverse_html: called CC=4 SCAR=13.9
265 {
266 # Plain text
267 9 ▶ return $class->new( $node ) if !ref $node;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $node 4 5 9
268  
269 5 my $tag = $node->tag;
270  
271 5 my $ret = $class->new;
272  
273 5 $ret .= _traverse_html( $class, $_ ) for $node->content_list;
274  
275 5 ▶ $ret->apply_tag( 0, length $ret, $tag, { $node->all_external_attr } )
Branch: 1 branch
BranchTrueFalseTotal
unless $tag eq "body" 3 2 5
276 unless $tag eq "body";
277  
278 5 return $ret;
279 }
280  
281 =head1 METHODS
282  
283 The following methods are provided in addition to those provided by
284 L<String::Tagged|String::Tagged/METHODS>.
285  
286 =cut
287  
288 46 ▶sub _escape_html ( $s )
Subroutine _escape_html: called CC=6 SCAR=17.9
289 {
290 46 ▶ $s =~ s/([<>&"'])/$1 eq "<" ? "&lt;" :
Branch: 5 branches
BranchTrueFalseTotal
$1 eq '<' ? : 2 6 8
$1 eq '>' ? : 3 3 6
$1 eq '&' ? : 1 2 3
$1 eq '"' ? : 1 1 2
$1 eq q['] ? : 1 0 1
291 $1 eq ">" ? "&gt;" :
292 $1 eq "&" ? "&amp;" :
293 $1 eq '"' ? "&quot;" :
294 $1 eq "'" ? "&#39;" : ""/eg;
295 46 $s;
296 }
297  
298 3 ▶sub _cmp_tag_values ( $self, $name, $v1, $v2 )
Subroutine _cmp_tag_values: called CC=4 SCAR=23.2
299 {
300 3 ▶ return ( $v1 == $v2 ) if grep { $name eq $_ } qw( b i u small strong em tt super sub );
Branch: 1 branch
BranchTrueFalseTotal
if grep {$name eq $_;} "b", "i", "u", "small", "strong", "em", "tt", "super", "sub" 3 0 3
301 0 ▶ return ( $v1->{href} eq $v2->{href} ) if $name eq "a";
Branch: 1 branch
BranchTrueFalseTotal
if $name eq "a" 0 0 0
302 0 ▶ return ( $v1->{style} eq $v2->{style} ) if $name eq "span";
Branch: 1 branch
BranchTrueFalseTotal
if $name eq "span" 0 0 0
303 0 die "String::Tagged::HTML does not recognise the tag name '$name'\n";
304 }
305  
306 =head2 as_html
307  
308 $html = $st->as_html( $element );
309  
310 Returns a string containing an HTML rendering of the current contents of the
311 object. If C<$element> is provided, the output will be wrapped in an element
312 of the given name. If not defined, no outer wrapping will be performed.
313  
314 =cut
315  
316 2 ▶sub _build_style ( $style )
Subroutine _build_style: called CC=1 SCAR=0.0
317 {
318 return join " ", map {
319 2 my $prop = $_ =~ s/_/-/gr;
320 3 "$prop: $style->{$_};"
321 } sort keys %$style;
322 }
323  
324 25 ▶sub as_html ( $self, $elem = undef )
Subroutine as_html: called CC=4 SCAR=13.9
Pod documented
325 25 {
326 25 my $ret = "";
327  
328 25 my @tags_in_effect; # of [ $name, $value ]
329  
330 $self->iter_extents_nooverlap(
331 36 ▶ sub ( $e, %tags ) {
Subroutine __ANON__: called CC=10 SCAR=23.0
332 # _span_style_... hackery
333 36 my %span_style;
334 36 foreach my $k ( grep m/^_/, keys %tags ) {
335 3 my $v = delete $tags{$k};
336 3 ▶ if( $k =~ m/^_span_style_(.*)$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k =~ /^_span_style_(.*)$/u) 3 0 3
337 3 $span_style{$1} = $v;
338 }
339 }
340 36 ▶ $tags{span}{style} = _build_style \%span_style if keys %span_style;
Branch: 1 branch
BranchTrueFalseTotal
if keys %span_style 2 34 36
341  
342 # Look for the first tag that no longer applies, as we'll have to
343 # unwind the entire tag stack to that point
344  
345 36 my $i;
346 36 ▶ for( $i = 0; $i < @tags_in_effect; $i++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @tags_in_effect) 7 32 39
347 7 my ( $tag, $value ) = $tags_in_effect[$i]->@*;
348 7 ▶ last if !exists $tags{$tag};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $tags{$tag} 4 3 7
349 3 ▶ last if !$self->_cmp_tag_values( $tag, $value, $tags{$tag} );
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_cmp_tag_values($tag, $value, $tags{$tag}) 0 3 3
350 3 delete $tags{$tag};
351 }
352  
353 36 ▶ while( @tags_in_effect > $i ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@tags_in_effect > $i) 5 36 41
354 5 my ( $tag ) = ( pop @tags_in_effect )->@*;
355 5 $ret .= "</$tag>";
356 }
357  
358 # TODO: Sort these into an optimal order
359 36 foreach my $tag ( keys %tags ) {
360 24 my $value = $tags{$tag};
361 24 ▶ if( ref $value eq "HASH" ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value eq 'HASH') { } 6 18 24
362 6 my $attrs = join "", map { qq( $_=") . _escape_html($value->{$_}) . q(") } sort keys %$value;
363 6 $ret .= "<$tag$attrs>";
364 }
365 else {
366 18 $ret .= "<$tag>";
367 }
368 24 push @tags_in_effect, [ $tag, $value ];
369 }
370  
371 $self->iter_substr_nooverlap(
372 43 ▶ sub ( $str, %tags ) {
Subroutine __ANON__: called CC=2 SCAR=6.9
373 43 ▶ $ret .= ( $tags{raw} ? $str : _escape_html( $str ) );
Branch: 1 branch
BranchTrueFalseTotal
$tags{'raw'} ? : 3 40 43
374 },
375 36 start => $e->start,
376 end => $e->end,
377 );
378 },
379 25 except => [qw( raw )],
380 );
381  
382 25 ▶ while( @tags_in_effect ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@tags_in_effect) 19 25 44
383 19 my ( $tag ) = ( pop @tags_in_effect )->@*;
384 19 $ret .= "</$tag>";
385 }
386  
387 25 ▶ return "<$elem>$ret</$elem>" if defined $elem;
Branch: 1 branch
BranchTrueFalseTotal
if defined $elem 1 24 25
388 24 return "$ret";
389 }
390  
391 =head1 AUTHOR
392  
393 Paul Evans <leonerd@leonerd.org.uk>
394  
395 =cut
396  
397 7 0x55AA;
↑ Summary