blib/lib/Markdown/Parser/Element.pm untested

filter: Statementstmt 0.0% 0 / 314 Branchbran 0.0% 0 / 130 Conditioncond 0.0% 0 / 41 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 82 Podpod 0.0% 0 / 73 totaltotal 0.0% 0 / 640 CC 66 SCAR 39.7
CC
66
Cov
0%
look
240.0
init
182.0
encode_html
90.0
CRAP 53.2
1 ##----------------------------------------------------------------------------
2 ## Markdown Parser Only - ~/lib/Markdown/Parser/Element.pm
3 ## Version v0.3.0
4 ## Copyright(c) 2022 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2021/08/23
7 ## Modified 2024/08/30
8 ## All rights reserved
9 ##
10 ## This program is free software; you can redistribute it and/or modify it
11 ## under the same terms as Perl itself.
12 ##----------------------------------------------------------------------------
13 package Markdown::Parser::Element;
14 BEGIN
15 {
16 use strict;
17 use warnings;
18 use warnings::register;
19 use parent qw( Module::Generic );
20 use vars qw( $VERSION );
21 use CSS::Object;
22 our $VERSION = 'v0.3.0';
23 };
24  
25 use strict;
26 use warnings;
27  
28 sub init
29 {
30 my $self = shift( @_ );
31 ## print( STDERR ref( $self ), "::new: Markdown::Parser::Element::init() Parameters provided are: '", join( "', '", @_ ), "'\n" );
32 my $opts = {};
33 $opts = shift( @_ ) if( $self->_is_hash( $_[0] ) );
34 if( !( scalar( @_ ) % 2 ) && scalar( keys( %$opts ) ) )
35 {
36 my $hash = { @_ };
37 my @keys = keys( %$hash );
38 @$opts{ @keys } = @$hash{ @keys };
39 }
40 elsif( !( scalar( @_ ) % 2 ) )
41 {
42 $opts = { @_ };
43 }
44 $self->{attr} = {} unless( CORE::exists( $self->{attr} ) );
45 $self->{children} = [] unless( CORE::exists( $self->{children} ) );
46 $self->{class} = [] unless( CORE::exists( $self->{class} ) );
47 ## To contain the CSS::Object
48 $self->{css} = '' unless( CORE::exists( $self->{css} ) );
49 ## Dictionary hash object of abbreviations
50 $self->{dict} = {} unless( CORE::exists( $self->{dict} ) );
51 $self->{parent} = '' unless( CORE::exists( $self->{parent} ) );
52 $self->{pos} = '' unless( CORE::exists( $self->{pos} ) );
53 $self->{raw} = '' unless( CORE::exists( $self->{raw} ) );
54 $self->{tag_name} = '' unless( CORE::exists( $self->{tag_name} ) );
55 $self->{_init_strict_use_sub} = 1;
56 ## print( STDERR ref( $self ), "::new: Calling SUPER::init with: ", $self->dump( $opts ) );
57 return( $self->SUPER::init( $opts ) );
58 ## $self->SUPER::init( $opts );
59 ## print( STDERR ref( $self ), "::new: Debug value: ", $self->debug, "\n" );
60 ## return( $self );
61 }
62  
63 sub add_attributes
64 {
65 my $self = shift( @_ );
66 ## A string something like {#id1} or {.cl} or {#id.cl.class}
67 my $def = shift( @_ );
68 return if( !length( $def ) );
69 my( @ids, @classes, @attributes );
70 while( $def =~ s/
71 [[:blank:]\h]*
72 (?<attr_name>[a-zA-Z][\w\-]+)
73 [[:blank:]\h]*
74 =
75 [[:blank:]\h]*
76 (?<quote>["'])?
77 (?(<quote>)
78 (?:(?<attr_value>.*?)\g{quote})
79 |
80 (?<attr_value>\S+)
81 )
82 //xs )
83 {
84 push( @attributes, [ $+{attr_name} => $+{attr_value} ] );
85 }
86 while( $def =~ s/[[:blank:]\h]*\#(?<id>[^[:space:]\h\.\#]+)//s )
87 {
88 push( @ids, $+{id} );
89 }
90 while( $def =~ s/[[:blank:]\h]*\.(?<class>[^[:space:]\h\.\#]+)//s )
91 {
92 push( @classes, $+{class} );
93 }
94 $self->id->push( @ids );
95 $self->class->push( @classes ) if( scalar( @classes ) );
96 if( scalar( @attributes ) )
97 {
98 foreach my $ref ( @attributes )
99 {
100 ## If the user had defined it twice, it might very well override previous data set
101 $self->attributes->set( $ref->[0] => $ref->[1] );
102 }
103 }
104 return( $self );
105 }
106  
107 sub add_element
108 {
109 my $self = shift( @_ );
110 my $obj = shift( @_ );
111 my $base = $self->base_class;
112 return( $self->error( "Element provided \"$obj\" is not an Markdown::Parser::Element object." ) ) if( !$self->_is_a( $obj, "${base}::Element" ) );
113 $obj->parent( $self );
114 $self->children->push( $obj );
115 return( $self );
116 }
117  
118 sub add_to
119 {
120 my $self = shift( @_ );
121 my $obj = shift( @_ );
122 return( $self->error( "Element provided \"$obj\" is not an Markdown::Parser::Element object." ) ) if( !$self->_is_a( $obj, 'Markdown::Parser::Element' ) );
123 $obj->children->push( $self );
124 return( $self );
125 }
126  
127 sub as_markdown
128 {
129 my $self = shift( @_ );
130 warn( "as_markdown method not implemented for ", ref( $self ), "\n" );
131 return;
132 }
133  
134 sub as_pod
135 {
136 my $self = shift( @_ );
137 warn( "as_pod method not implemented for ", ref( $self ), "\n" );
138 return;
139 }
140  
141 sub as_string
142 {
143 my $self = shift( @_ );
144 warn( "as_string method not implemented for ", ref( $self ), "\n" );
145 return;
146 }
147  
148 sub attr { return( shift->_set_get_hash_as_mix_object( 'attr', @_ ) ); }
149  
150 # Alias
151 sub attributes { return( shift-> _set_get_hash_as_mix_object( 'attr', @_ ) ); }
152  
153 sub base_class
154 {
155 my $self = shift( @_ );
156 my $class = ref( $self ) || $self;
157 my @frag = split( /\::/, $class );
158 return( join( '::', @frag[ 0..( $#frag-1 ) ] ) );
159 }
160  
161 sub children { return( shift->_set_get_array_as_object( 'children', @_ ) ); }
162  
163 sub class { return( shift->_set_get_array_as_object( 'class', @_ ) ); }
164  
165 # Returns the closest non-new line element or the one specified
166 sub closest
167 {
168 my $self = shift( @_ );
169 my $target;
170 $target = shift( @_ ) if( @_ );
171 my $elem;
172 # Starting from the latest to the oldest
173 $self->children->reverse->foreach(sub
174 {
175 return(1) if( $_->tag_name eq 'nl' );
176 # We exit (return false) after the first element we found if there is no target specified
177 if( !defined( $target ) ||
178 ( defined( $target ) && $_->tag_name eq $target ) )
179 {
180 $elem = $_;
181 return;
182 }
183 return(1);
184 });
185 return( $elem );
186 }
187  
188 sub create_abbreviation { return( shift->_create_element( 'Abbr', @_ ) ); }
189  
190 sub create_blockquote { return( shift->_create_element( 'Blockquote', @_ ) ); }
191  
192 sub create_bold { return( shift->_create_element( 'Bold', @_ ) ); }
193  
194 sub create_checkbox { return( shift->_create_element( 'Checkbox', @_ ) ); }
195  
196 sub create_code { return( shift->_create_element( 'Code', @_ ) ); }
197  
198 sub create_em { return( shift->_create_element( 'Emphasis', @_ ) ); }
199  
200 sub create_footnote { return( shift->_create_element( 'Footnote', @_ ) ); }
201  
202 sub create_footnote_ref { return( shift->_create_element( 'FootnoteReference', @_ ) ); }
203  
204 sub create_header { return( shift->_create_element( 'Header', @_ ) ); }
205  
206 sub create_image { return( shift->_create_element( 'Image', @_ ) ); }
207  
208 sub create_html { return( shift->_create_element( 'HTML', @_ ) ); }
209  
210 sub create_insertion { return( shift->_create_element( 'Insertion', @_ ) ); }
211  
212 sub create_line { return( shift->_create_element( 'Line', @_ ) ); }
213  
214 sub create_link_definition { return( shift->_create_element( 'LinkDefinition', @_ ) ); }
215  
216 sub create_link { return( shift->_create_element( 'Link', @_ ) ); }
217  
218 sub create_list { return( shift->_create_element( 'List', @_ ) ); }
219  
220 sub create_list_item { return( shift->_create_element( 'ListItem', @_ ) ); }
221  
222 sub create_new_line { return( shift->_create_element( 'NewLine', @_ ) ); }
223  
224 sub create_paragraph { return( shift->_create_element( 'Paragraph', @_ ) ); }
225  
226 sub create_strikethrough { return( shift->_create_element( 'StrikeThrough', @_ ) ); }
227  
228 sub create_subscript { return( shift->_create_element( 'Subscript', @_ ) ); }
229  
230 sub create_superscript { return( shift->_create_element( 'Superscript', @_ ) ); }
231  
232 sub create_table { return( shift->_create_element( 'Table', @_ ) ); }
233  
234 sub create_table_body { return( shift->_create_element( 'TableBody', @_ ) ); }
235  
236 sub create_table_caption { return( shift->_create_element( 'TableCaption', @_ ) ); }
237  
238 sub create_table_cell { return( shift->_create_element( 'TableCell', @_ ) ); }
239  
240 sub create_table_column { return( shift->_create_element( 'TableColumn', @_ ) ); }
241  
242 sub create_table_header { return( shift->_create_element( 'TableHeader', @_ ) ); }
243  
244 sub create_table_row { return( shift->_create_element( 'TableRow', @_ ) ); }
245  
246 sub create_text { return( shift->_create_element( 'Text', @_ ) ); }
247  
248 sub css { return( shift->_set_get_object( 'css', 'CSS::Object', @_ ) ); }
249  
250 sub css_inline
251 {
252 return( CSS::Object->new( format => 'CSS::Object::Format::Inline' ) );
253 }
254  
255 sub detach
256 {
257 my $self = shift( @_ );
258 my $arr = $self->children->clone;
259 $self->children->reset;
260 return( $arr );
261 }
262  
263 sub document { return( shift->_set_get_object( 'document', 'Markdown::Parser::Document', @_ ) ); }
264  
265 sub empty
266 {
267 my $self = shift( @_ );
268 $self->children->reset;
269 return( $self );
270 }
271  
272 sub encode_html
273 {
274 my $self = shift( @_ );
275 my( $what, $text ) = @_;
276 return if( !defined( $text ) );
277 my $map =
278 {
279 '<' => '&lt;',
280 '>' => '&gt;',
281 ## Also &#38;
282 '&' => '&amp;',
283 ## Also &#63;
284 '?' => '&quest;',
285 ## Also known as &num;
286 '#' => '&#35;',
287 '"' => '&quot;',
288 "'" => '&#39;',
289 };
290 my $data = $self->_is_scalar( $text ) ? $text : \$text;
291 $what = [keys( %$map )] if( $what eq 'all' );
292 return( $self->error( "List of items to encode is not an array reference." ) ) if( !$self->_is_array( $what ) );
293 return( $$data ) if( !scalar( @$what ) );
294 ## return( $self->error( "Text to encode is not a scalar reference." ) ) if( !$self->_is_scalar( $text ) );
295 my $todo = {};
296 ## Make a hash of characters to encode
297 @$todo{ @$what } = ( 1 ) x scalar( @$what );
298 if( my $amp = delete( $todo->{ '&' } ) )
299 {
300 ## 1 while( $$data =~ s/(?<!\\)(\&)(?!\d+\;)/$map->{ $1 }/gs );
301 $$data =~ s/(?<!\\)(\&)(?!(?:amp|gt|lt)\;)/$map->{ $1 }/gs;
302 }
303 if( my $amp = delete( $todo->{ '#' } ) )
304 {
305 ## 1 while( $$data =~ s/(?<!\\)(\#)(?!(?:amp|gt|lt)\;)/$map->{ $1 }/gs );
306 $$data =~ s/(?:(?<!\\)|(?<!\&))(\#)(?!\d+\;)/$map->{ $1 }/gs;
307 }
308 if( scalar( %$todo ) )
309 {
310 my $re = join( '|', map( quotemeta( $_ ), keys( %$todo ) ) );
311 ## 1 while( $$data =~ s/(?<!\\)($re)/$map->{ $1 }/gs );
312 $$data =~ s/(?<!\\)($re)/$map->{ $1 }/gs;
313 }
314 # return( $self );
315 return( $$data );
316 }
317  
318 sub extract_links
319 {
320 my $self = shift( @_ );
321 # my $links = $self->new_array;
322 # $self->children->for(sub
323 # {
324 # my( $i, $link ) = @_;
325 # if( $self->_is_a( $link => 'Markdown::Parser::Link' ) )
326 # {
327 # $links->push( $link );
328 # }
329 # if( $link->children->length > 0 )
330 # {
331 # my $more_links = $link->extract_links;
332 # $links->push( $more_links->list ) if( $more_links->length );
333 # }
334 # });
335 my $links = $self->look_down( tag => 'link' );
336 return( $links );
337 }
338  
339 sub format_attributes
340 {
341 my $self = shift( @_ );
342 my $attr = $self->attributes;
343 ## Return an empty array if there is nothing
344 return( $self->new_array ) if( !$attr->length );
345 return( $attr->map_array(sub{ sprintf( '%s="%s"', $_, $attr->{ $_ } ) }) );
346 }
347  
348 sub format_class
349 {
350 my $self = shift( @_ );
351 if( $self->class->length )
352 {
353 return( sprintf( 'class="%s"', $self->class->join( ' ' )->scalar ) );
354 }
355 return( '' );
356 }
357  
358 sub format_id
359 {
360 my $self = shift( @_ );
361 if( $self->id->length )
362 {
363 return( sprintf( 'id="%s"', $self->id->join( ' ' )->scalar ) );
364 }
365 return( '' );
366 }
367  
368 sub id { return( shift->_set_get_array_as_object( 'id', @_ ) ); }
369  
370 sub insert_after
371 {
372 my $self = shift( @_ );
373 my $elem = shift( @_ );
374 return if( !length( $elem ) );
375 my $base_class = $self->base_class;
376 return( $self->error( "Element provided is not ${base_class}::Element object." ) ) if( !$self->_is_a( "${base_class}::Element", $elem ) );
377 return if( !$self->parent );
378 my $children = $self->parent->children;
379 my $pos = $children->pos( $self );
380 return if( !defined( $pos ) );
381 $children->splice( $pos + 1, 0, $elem );
382 return( $elem );
383 }
384  
385 sub insert_before
386 {
387 my $self = shift( @_ );
388 my $elem = shift( @_ );
389 return if( !length( $elem ) );
390 my $base_class = $self->base_class;
391 return( $self->error( "Element provided is not ${base_class}::Element object." ) ) if( !$self->_is_a( "${base_class}::Element", $elem ) );
392 return if( !$self->parent );
393 my $children = $self->parent->children;
394 my $pos = $children->pos( $self );
395 return if( !defined( $pos ) );
396 $children->splice( $pos, 0, $elem );
397 return( $elem );
398 }
399  
400 sub look
401 {
402 my $self = shift( @_ );
403 my $opts = $self->_get_args_as_hash( @_ );
404 $opts->{direction} //= 'down';
405 unless( $opts->{direction} eq 'down' ||
406 $opts->{direction} eq 'up' )
407 {
408 return( $self->error( "Unknown direction provided '$opts->{direction}'" ) );
409 }
410 my $a = $self->new_array;
411 my( $check_elem, $crawl_down );
412 $check_elem = sub
413 {
414 my $e = shift( @_ );
415 my $def = shift( @_ );
416 $def->{level} //= 0;
417 # Assume not ok, then check otherwise
418 my $ok = 0;
419 if( defined( $opts->{tag} ) && length( $opts->{tag} ) )
420 {
421 if( ref( $opts->{tag} ) eq 'Regexp' )
422 {
423 $ok = 1 if( $e->tag_name =~ /$opts->{tag}/ );
424 }
425 else
426 {
427 $ok = 1 if( $e->tag_name eq $opts->{tag} );
428 }
429 }
430 if( defined( $opts->{class} ) && length( $opts->{class} ) )
431 {
432 $ok = $self->_is_a( $e => $opts->{class} ) ? 1 : 0;
433 }
434
435 # We passed all checks, no checking our children
436 $a->push( $e ) if( $ok );
437 # Stop here since we reached the maximum number of matches
438 return if( CORE::exists( $opts->{max_match} ) && $a->length >= $opts->{max_match} );
439 # Don't go down or up further if we reached the maximum level
440 return(1) if( CORE::exists( $opts->{max_level} ) && ( $def->{level} + 1 ) > $opts->{max_level} );
441 $def->{level}++;
442 if( $opts->{direction} eq 'down' )
443 {
444 $crawl_down->( $e->children, $def ) if( $e->children->length > 0 );
445 }
446 elsif( $opts->{direction} eq 'up' )
447 {
448 $check_elem->( $e->parent ) if( $e->parent );
449 }
450 $def->{level}--;
451 return(1);
452 };
453
454 $crawl_down = sub
455 {
456 my $kids = shift( @_ );
457 my $def = shift( @_ );
458 $kids->foreach(sub
459 {
460 $check_elem->( $_, $def );
461 });
462 };
463
464 my $def = { level => 0 };
465 $check_elem->( $self, $def );
466 # return( $a->length > 0 ? $a : '' );
467 return( $a );
468 }
469  
470 sub look_down
471 {
472 my $self = shift( @_ );
473 my $opts = $self->_get_args_as_hash( @_ );
474 $opts->{direction} = 'down';
475 return( $self->look( $opts ) );
476 }
477  
478 sub look_up
479 {
480 my $self = shift( @_ );
481 my $opts = $self->_get_args_as_hash( @_ );
482 $opts->{direction} = 'up';
483 return( $self->look( $opts ) );
484 }
485  
486 sub make_html_parser
487 {
488 my $self = shift( @_ );
489 require HTML::Object;
490 return( HTML::Object->new );
491 }
492  
493 sub object_id
494 {
495 my $self = shift( @_ );
496 return( $self->{object_id} ) if( length( $self->{object_id} ) );
497 $self->{object_id} = Scalar::Util::refaddr( $self );
498 return( $self->{object_id} );
499 }
500  
501 sub package { return( ref( $_[0] ) ); }
502  
503 sub parent { return( shift->_set_get_object( 'parent', 'Markdown::Parser::Element', @_ ) ); }
504  
505 sub parse_html
506 {
507 my $self = shift( @_ );
508 my $html = shift( @_ ) || return;
509 my $p = $self->make_html_parser;
510 my $doc = $p->parse_data( $html ) ||
511 return( $self->pass_error( $p->error ) );
512 return( $doc );
513 }
514  
515 sub pos { return( shift->_set_get_number_as_object( 'pos', @_ ) ); }
516  
517 sub raw { return( shift->_set_get_scalar_as_object( 'raw', @_ ) ); }
518  
519 sub remove
520 {
521 my $self = shift( @_ );
522 if( @_ )
523 {
524 my $elem = shift( @_ );
525 return if( !length( $elem ) );
526 my $base_class = $self->base_class;
527 return( $self->error( "Element provided is not a ${base_class}::Element object." ) ) if( !$self->_is_a( "${base_class}::Element", $elem ) );
528 my $pos = $self->children->pos( $elem );
529 return if( !defined( $pos ) );
530 return( $self->children->delete( $pos, 1 ) );
531 }
532 ## Called without argument: remove itself from its parent
533 elsif( $self->_is_object( $self->parent ) )
534 {
535 return( $self->parent->remove( $self ) );
536 }
537 return;
538 }
539  
540 sub remove_children { return( shift->children->reset ); }
541  
542 sub tag_name { return( shift->_set_get_scalar_as_object( 'tag_name', @_ ) ); }
543  
544 sub wrap
545 {
546 my $self = shift( @_ );
547 my $elem = shift( @_ );
548 my $base_class = $self->base_class;
549 return( $self->error( "Element provided to wrap children is not a ${base_class}::Element object." ) ) if( !$self->_is_a( $elem, "${base_class}::Element" ) );
550 ## Copy our children to the element provided and set the parent property accordingly
551 $self->children->foreach(sub
552 {
553 $elem->add_element( $_ );
554 });
555 $self->remove_children;
556 ## Set this element as our only child and set the parent property accordingly
557 $self->add_element( $elem );
558 return( $self );
559 }
560  
561 sub _append_text
562 {
563 my $self = shift( @_ );
564 my $what = shift( @_ ) || return;
565 my $elem_class = $self->base_class . '::Element';
566 if( $self->_is_a( $what, $elem_class ) )
567 {
568 $self->children->push( $what );
569 }
570 elsif( ref( $what ) )
571 {
572 return( $self->error( "I do not know what to do with this reference \"$what\". I was expecting either a string or a $elem_class class object." ) );
573 }
574 ## Simple string, i.e. a text chunk
575 else
576 {
577 if( $self->children->last->tag_name eq 'text' )
578 {
579 $self->children->last->append( " $what" );
580 }
581 else
582 {
583 $self->children->push( $self->create_text({
584 text => $what,
585 raw => $what,
586 }) );
587 }
588 }
589 return( $self );
590 }
591  
592 sub _create_element
593 {
594 my $self = shift( @_ );
595 my $mod = shift( @_ );
596 my $base = $self->base_class;
597 my $class = "${base}::${mod}";
598 $self->_load_class( $class ) || return;
599 my $obj = $class->new( @_, debug => $self->debug ) || return( $self->pass_error( $class->error ) );
600 ## Assign the top document object, which is used by children element to access the document object methods
601 if( $self->isa( 'Markdown::Parser::Document' ) )
602 {
603 $obj->document( $self );
604 }
605 elsif( my $doc = $self->document )
606 {
607 $obj->document( $doc );
608 }
609 return( $obj );
610 }
611  
612 1;
613 # NOTE: POD
614 __END__