blib/lib/HTML/Object/Element.pm untested

filter: Statementstmt 0.0% 0 / 913 Branchbran 0.0% 0 / 390 Conditioncond 0.0% 0 / 274 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 109 Podpod 0.0% 0 / 95 totaltotal 0.0% 0 / 1781 CC 196 SCAR 47.4
CC
196
Cov
0%
look
600.0
as_string
420.0
new_from_lol
240.0
CRAP 114.2
1 ##----------------------------------------------------------------------------
2 ## HTML Object - ~/lib/HTML/Object/Element.pm
3 ## Version v0.3.1
4 ## Copyright(c) 2026 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2021/04/25
7 ## Modified 2026/07/04
8 ## All rights reserved.
9 ##
10 ##
11 ## This program is free software; you can redistribute it and/or modify it
12 ## under the same terms as Perl itself.
13 ##----------------------------------------------------------------------------
14 package HTML::Object::Element;
15 BEGIN
16 {
17 # For smart match
18 use v5.10.1;
19 use strict;
20 use warnings;
21 warnings::register_categories( 'HTML::Object' );
22 use parent qw( Module::Generic );
23 use vars qw( $LOOK_LIKE_HTML $LOOK_LIKE_IT_HAS_HTML $ATTRIBUTE_NAME_RE $VERSION );
24 use Data::UUID;
25 use Digest::MD5 ();
26 use Encode ();
27 use Scalar::Util ();
28 use Wanted;
29 use overload (
30 'eq' => \&_same_as,
31 '==' => \&_same_as,
32 fallback => 1,
33 );
34 our $LOOK_LIKE_HTML = qr/^[[:blank:]\h]*\<\w+.*?\>/;
35 our $LOOK_LIKE_IT_HAS_HTML = qr/\<\w+.*?\>/;
36 our $ATTRIBUTE_NAME_RE = qr/\w[\w\-]*/;
37 our $VERSION = 'v0.3.1';
38 };
39  
40 use strict;
41 use warnings;
42  
43 sub init
44 {
45 my $self = shift( @_ );
46 my $opts = $self->_get_args_as_hash( @_ );
47 for( qw( attributes attributes_sequence ) )
48 {
49 delete( $opts->{ $_ } ) if( !defined( $opts->{ $_ } ) );
50 }
51 my $parent = delete( $opts->{parent} );
52 $opts->{parent} = $parent;
53 $self->{attr} = {} unless( exists( $self->{attr} ) );
54 $self->{attr_seq} = [] unless( exists( $self->{attr_seq} ) );
55 $self->{checksum} = '';
56 $self->{close_tag} = '' unless( exists( $self->{close_tag} ) );
57 $self->{column} = 0;
58 # Was there a closing tag for non-void tags?
59 $self->{is_closed} = 0 unless( exists( $self->{is_closed} ) );
60 $self->{is_empty} = 0 unless( exists( $self->{is_empty} ) );
61 $self->{line} = 0;
62 $self->{modified} = 0;
63 $self->{offset} = 0;
64 $self->{original} = undef;
65 $self->{parent} = undef;
66 $self->{rank} = undef;
67 $self->{tag} = '' unless( exists( $self->{tag} ) );
68 $self->{_init_strict_use_sub} = 1;
69 $self->{_exception_class} = 'HTML::Object::Exception';
70 $self->SUPER::init( $opts ) || return( $self->pass_error );
71 $self->{children} = [];
72 # uuid
73 $self->{eid} = $self->_generate_uuid();
74 # The user is always right, so we check if the tag has a forward slash as attribute
75 # If there is one, this means this tag is an empty (void) tag.
76 # We issue a warning if our dictionary-derived value 'is_empty' says different
77 $opts->{is_empty} = 0 if( !exists( $opts->{is_empty} ) );
78 $opts->{attributes} = {} if( !exists( $opts->{attributes} ) );
79 my $attr = $opts->{attributes};
80 if( !$opts->{is_empty} && exists( $attr->{'/'} ) )
81 {
82 warn( "Tag initiated \"$opts->{tag}\" is marked as non-empty (non-void), but ends with \"/>\" at line $opts->{line} and column $opts->{column}: $opts->{original}\n" ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
83 $self->is_empty(1);
84 }
85 $self->checksum( $self->set_checksum );
86 $self->{_cache_value} = '';
87 $self->{_internal} = {};
88 return( $self );
89 }
90  
91 # Note: HTML::Element compatibility
92 sub address
93 {
94 my $self = shift( @_ );
95 if( @_ )
96 {
97 my $addr = shift( @_ );
98 my $path = $self->new_array( [split( /\./, $addr )] );
99 my $root;
100 # relative path, such as .2.5.3
101 if( !length( $path->[0] ) )
102 {
103 $root = $self;
104 }
105 else
106 {
107 $root = $self->root;
108 return( $self->error( "First offset position should be 0 for root or a relative path." ) ) if( $path->shift != 0 );
109 }
110 my $offset;
111 while( $path->length && ( $offset = $path->shift ) )
112 {
113 return( $self->error( "Invalid offset '$offset' in path '$addr'. Value is bigger than the actual size of elements (", $root->children->size, "); starting from 0." ) ) if( $offset > $root->children->size );
114 $root = $root->children->get( $offset );
115 }
116 return( $root );
117 }
118 else
119 {
120 my $line = $self->new_array;
121 my $pos = $self->pos || 0;
122 $line->push( $pos );
123 $line->push( $self->lineage->list );
124 return( $line->reverse->join( '.' ) );
125 }
126 }
127  
128 # Note: HTML::Element compatibility
129 sub all_attr
130 {
131 my $self = shift( @_ );
132 my $ref = $self->attributes;
133 return( %$ref );
134 }
135  
136 # Note: HTML::Element compatibility
137 sub all_attr_names
138 {
139 my $self = shift( @_ );
140 return( $self->attributes->keys->list );
141 }
142  
143 sub as_html { return( shift->as_string( @_ ) ); }
144  
145 sub as_string
146 {
147 my $self = shift( @_ );
148 my $opts = $self->_get_args_as_hash( @_ );
149 # If the element is called from within a collection, although it still has its
150 # parent, we do not know exactly where is its closing tag, if any.
151 # So this option makes it possible to return the tag and its closing tag, if any.
152 $opts->{inside_collection} = 0 if( !CORE::exists( $opts->{inside_collection} ) );
153 $opts->{inside_collection} //= 0;
154 $opts->{recursive} //= 0;
155 return( $self->{_cache_value} ) if( $self->{_cache_value} && !CORE::length( $self->{_reset} ) );
156 my $tag = $self->tag;
157 my $res = $self->new_array;
158 my $a = $self->new_array( ["<${tag}"] );
159 my $hash1 = $self->checksum;
160 my $hash2 = $self->set_checksum;
161 if( $self->original->defined && $hash1 eq $hash2 )
162 {
163 $a->set( [ $self->original->scalar ] );
164 }
165 else
166 {
167 if( !$self->attributes_sequence->is_empty )
168 {
169 my $attr = $self->new_array;
170 $self->attributes_sequence->foreach(sub
171 {
172 my $k = shift( @_ );
173 return(1) if( $k eq '/' );
174 my $v = $self->attributes->get( $k );
175 return if( !defined( $v ) );
176 # Ensure double quotes are escaped
177 $v =~ s/(?<!\\)\"/\\\"/gs;
178 $attr->push( sprintf( '%s="%s"', $k, $v ) );
179 });
180 $a->push( $attr->join( ' ' )->scalar );
181 }
182 }
183 if( !$self->children->is_empty )
184 {
185 if( $self->is_empty )
186 {
187 warn( "This tag \"$tag\" is supposed to be an empty / void one, but it has " . $self->children->length . " children.\n" ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
188 }
189 # The user is alway right, so let's add those children
190 $res->push( $a->join( ' ' )->scalar );
191 $res->push( '>' ) unless( $self->original->defined && $hash1 eq $hash2 );
192 $self->children->foreach(sub
193 {
194 my $e = shift( @_ );
195 my $v;
196 if( $opts->{as_xml} )
197 {
198 $v = $e->as_xml( recursive => 1 );
199 }
200 else
201 {
202 $v = $e->as_string( recursive => 1 );
203 }
204 $res->push( defined( $v ) ? $v->scalar : $v );
205 });
206 # $res->push( "</${tag}>" );
207 # $res->push( "</${tag}>" ) if( !$self->parent && !$self->is_empty );
208 # if( ( $opts->{inside_collection} || !$opts->{recursive} ) && $self->close_tag )
209 if( my $close = $self->close_tag )
210 {
211 my $parent = $self->parent;
212 unless( $parent && defined( my $pos = $parent->children->pos( $close ) ) )
213 {
214 $res->push( $close->as_string );
215 }
216 }
217 }
218 else
219 {
220 if( $self->is_empty )
221 {
222 # No need to add this, because we are re-using the original tag data since it has not changed
223 $a->push( '/>' ) unless( $hash1 eq $hash2 );
224 $res->push( $a->join( ' ' )->scalar );
225 }
226 else
227 {
228 $res->push( $a->join( ' ' )->scalar );
229 $res->push( '>' ) unless( $self->original->defined && $hash1 eq $hash2 );
230 # If it has a parent, the parent will contain the closing tag, but
231 # If this element is an element created with a find, such as $('body'), it has no
232 # parent.
233 # $res->push( "</${tag}>" ) if( !$self->parent && !$self->is_empty );
234 if( my $close = $self->close_tag )
235 {
236 my $parent = $self->parent;
237 unless( $parent && defined( my $pos = $parent->children->pos( $close ) ) )
238 {
239 $res->push( $close->as_string );
240 }
241 }
242 }
243 }
244 my $elem = $res->join( '' );
245 $self->{_cache_value} = $elem;
246 CORE::delete( $self->{_reset} );
247 return( $elem );
248 }
249  
250 # Note: HTML::Element compatibility
251 sub as_text
252 {
253 my $self = shift( @_ );
254 return( $self->{_cache_text} ) if( $self->{_cache_text} && !CORE::length( $self->{_reset} ) );
255 my $opts = $self->_get_args_as_hash( @_ );
256 $opts->{unescape} //= 0;
257 my $a = $self->new_array;
258 my $seen = {};
259 my $crawl;
260 $crawl = sub
261 {
262 my $elem = shift( @_ );
263 $elem->children->foreach(sub
264 {
265 my $e = shift( @_ );
266 my $addr = Scalar::Util::refaddr( $e );
267 return(1) if( CORE::exists( $seen->{ $addr } ) );
268 $seen->{ $addr }++;
269 if( $e->isa( 'HTML::Object::Text' ) ||
270 $e->isa( 'HTML::Object::Space' ) )
271 {
272 if( exists( $opts->{callback} ) && ref( $opts->{callback} ) eq 'CODE' )
273 {
274 # If value returned is not true, we skip this element
275 $opts->{callback}->( $e ) || return(1);
276 }
277 if( $opts->{unescape} )
278 {
279 my $txt = $e->as_string->scalar;
280 $txt =~ s,<br[[:blank:]]*/>\n,\n,gs;
281 $txt =~ s/\&gt;/>/gs;
282 $txt =~ s/\&lt;/</gs;
283 $a->push( $txt );
284 }
285 else
286 {
287 $a->push( $e->as_string->scalar );
288 }
289 }
290  
291 unless( $e->isa( 'HTML::Object::Text' ) ||
292 $e->isa( 'HTML::Object::Space' ) )
293 {
294 $crawl->( $e );
295 }
296 });
297 };
298 if( $self->isa( 'HTML::Object::Text' ) ||
299 $self->isa( 'HTML::Object::Space' ) )
300 {
301 if( $opts->{unescape} )
302 {
303 my $txt = $self->value->scalar;
304 $txt =~ s,<br[[:blank:]]*/>\n,\n,gs;
305 $txt =~ s/\&gt;/>/gs;
306 $txt =~ s/\&lt;/</gs;
307 $a->push( $txt );
308 }
309 else
310 {
311 $a->push( $self->value->scalar );
312 }
313 }
314 else
315 {
316 $crawl->( $self );
317 }
318 $self->{_cache_text} = $a->join( '' );
319 CORE::delete( $self->{_reset} );
320 return( $self->{_cache_text} );
321 }
322  
323 # Note: HTML::Element compatibility
324 sub as_trimmed_text
325 {
326 my $self = shift( @_ );
327 my $opts = $self->_get_args_as_hash( @_ );
328 my $text = $self->as_text( $opts ) || return;
329 $text->replace( qr/^[[:blank:]\h\v]+|[[:blank:]\h\v]+$/, '' );
330 return( $text );
331 }
332  
333 # Note: HTML::Element compatibility
334 # This does the same as for html. Sub classes take care of the differences
335 # sub as_xml { return( shift->as_string( @_ ) ); }
336 sub as_xml
337 {
338 my $self = shift( @_ );
339 my $opts = $self->_get_args_as_hash( @_ );
340 $opts->{as_xml} = 1;
341 return( $self->as_string( $opts ) );
342 }
343  
344 sub attr
345 {
346 my $self = shift( @_ );
347 my $attr = shift( @_ ) || return( $self->error( "No attribute name provided." ) );
348 return( $self->error( "Attribute provided \"${attr}\" contains illegal characters. Only alphanumeric and _ are supported." ) ) if( $attr !~ /^\w+$/ );
349 if( @_ )
350 {
351 my $v = shift( @_ );
352 my $old;
353 if( defined( $v ) )
354 {
355 $old = $self->attributes->get( $attr );
356 # We do not want to force stringification, because for attribute like 'href' it could have an URI object as a value.
357 # When stringification will be required, it will be done automatically anyway.
358 # $v = "$v" if( ref( $v ) && overload::Method( $v, '""' ) );
359 $v =~ s/^[[:blank:]\h]+|[[:blank:]\h]+$//g if( !ref( $v ) );
360 $self->attributes->set( $attr => $v );
361 $self->attributes_sequence->push( $attr ) if( !$self->attributes_sequence->has( $attr ) );
362 }
363 else
364 {
365 $self->attributes_sequence->remove( $attr );
366 $old = $self->attributes->delete( $attr );
367 }
368  
369 # Check for attributes callback and execute it.
370 # This is typically used for HTML::Object::TokenList by HTML::Object::DOM::Element and HTML::Object::DOM::AnchorElement
371 my $callbacks = $self->{_internal_attribute_callbacks};
372 $callbacks = {} if( ref( $callbacks ) ne 'HASH' );
373 if( CORE::exists( $callbacks->{ $attr } ) && ref( $callbacks->{ $attr } ) eq 'CODE' )
374 {
375 my $cb = $callbacks->{ $attr };
376 # try-catch
377 local $@;
378 eval
379 {
380 $cb->( $self, $v );
381 };
382 if( $@ )
383 {
384 return( $self->error( "Error executing attribute callback for attribute \"$attr\" for element with tag \"", $self->tag, "\": $@" ) );
385 }
386 }
387 $self->reset(1);
388 return( $old );
389 }
390 else
391 {
392 return( $self->attributes->get( $attr ) );
393 }
394 }
395  
396 sub attributes { return( shift->reset(@_)->_set_get_hash_as_mix_object( 'attr', @_ ) ); }
397  
398 sub attributes_sequence
399 {
400 my $self = shift( @_ );
401 unless( @_ )
402 {
403 if( $self->_set_get_array_as_object( 'attr_seq' )->sort != $self->attributes->keys->sort )
404 {
405 $self->_set_get_array_as_object( 'attr_seq', $self->attributes->keys->sort );
406 }
407 }
408 return( $self->reset(@_)->_set_get_array_as_object( 'attr_seq', @_ ) );
409 }
410  
411 sub checksum { return( shift->reset(@_)->_set_get_scalar_as_object( 'checksum', @_ ) ); }
412  
413 sub children { return( shift->reset(@_)->_set_get_object_array_object( 'children', 'HTML::Object::Element', @_ ) ); }
414  
415 sub class { return( ref( $_[0] ) ); }
416  
417 # Note: HTML::Element compatibility
418 sub clone
419 {
420 my $self = shift( @_ );
421 my $parent = $self->parent;
422 $self->parent( undef );
423 # Array reference of HTML::Object::Element objects
424 my $kids = $self->children;
425 $self->children( [] );
426 my $new = $self->SUPER::clone();
427  
428 # NOTE: temporary diagnostic — body carries nearly all the document's
429 # real weight; dump its own fields by size the same way we did for
430 # Document, to find what's still duplicating something further down.
431 if( $self->tag eq 'body' )
432 {
433 foreach my $k ( sort { total_size( $self->{ $b } ) <=> total_size( $self->{ $a } ) } CORE::keys( %$self ) )
434 {
435 next unless( ref( $self->{ $k } ) );
436 }
437 # NOTE: drill one level deeper into close_tag itself, since it weighs
438 # disproportionately (24KB) for what should be a trivial marker object.
439 if( ref( $self->{close_tag} ) )
440 {
441 foreach my $k ( CORE::keys( %{ $self->{close_tag} } ) )
442 {
443 next unless( ref( $self->{close_tag}->{ $k } ) );
444 }
445 }
446 # NOTE: drill into a single Module::Generic::Number instance itself
447 # (body's own 'line' field) — every such field weighs an identical
448 # 10.09KB regardless of context, suggesting something inside the
449 # Number class itself, not the tree structure, is responsible.
450 if( ref( $self->{line} ) )
451 {
452 foreach my $k ( CORE::keys( %{ $self->{line} } ) )
453 {
454 my $v = $self->{line}->{ $k };
455 if( ref( $v ) )
456 {
457 }
458 else
459 {
460 }
461 }
462 }
463 }
464  
465 $new->{eid} = $self->_generate_uuid();
466 $self->parent( $parent );
467 $self->children( $kids );
468 my $children = $self->clone_list;
469 $new->children( $children );
470 $children->foreach(sub
471 {
472 shift->parent( $new );
473 });
474 $new->parent( undef );
475 $new->reset(1);
476 return( $new );
477 }
478  
479 # Note: HTML::Element compatibility
480 sub clone_list
481 {
482 my $self = shift( @_ );
483 my $a = $self->new_array;
484 $self->children->foreach(sub
485 {
486 my $e = shift( @_ );
487 $a->push( $e->clone );
488 });
489 return( $a );
490 }
491  
492 sub close
493 {
494 my $self = shift( @_ );
495 my $opts = $self->_get_args_as_hash( @_ );
496 # No need to close
497 return( $self ) if( $self->is_empty );
498 # if( !$parent )
499 # {
500 # warn( "No parent set for this element \"" . $self->tag . "\".\n" ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
501 # return( $self );
502 # }
503 my $e = $self->new_closing({
504 attributes => $opts->{attr},
505 attributes_sequence => $opts->{seq},
506 column => $opts->{col},
507 line => $opts->{line},
508 offset => $opts->{offset},
509 original => $opts->{raw},
510 tag => $self->tag,
511 debug => $self->debug,
512 }) || return( $self->pass_error );
513 my $parent = $self->parent;
514 if( $parent )
515 {
516 my $pos = $parent->children->pos( $self );
517 return( $self->error( "Could not find the opening tag '", $self->tag, "' in our parent." ) ) if( !defined( $pos ) );
518 # We place the closing tag in the parent's child right after our opening tag
519 # $parent->children->splice( $pos + 1, 0, $e );
520 }
521 $self->is_closed(1);
522 $self->close_tag( $e );
523 $self->reset(1);
524 return( $self );
525 }
526  
527 sub close_tag { return( shift->reset(@_)->_set_get_object( 'close_tag', 'HTML::Object::Element', @_ ) ); }
528  
529 sub column { return( shift->reset(@_)->_set_get_number_as_object( 'column', @_ ) ); }
530  
531 # Note: HTML::Element compatibility
532 sub content { return( shift->children ); }
533  
534 # Note: HTML::Element compatibility
535 sub content_array_ref { return( shift->children ); }
536  
537 # Note: HTML::Element compatibility
538 sub content_list
539 {
540 my $self = shift( @_ );
541 if( want( 'LIST' ) )
542 {
543 return( $self->children->list );
544 }
545 else
546 {
547 return( $self->children->length );
548 }
549 }
550  
551 # Note: HTML::Element compatibility
552 sub delete
553 {
554 my $self = shift( @_ );
555 $self->delete_content;
556 $self->detach;
557 %$self = ();
558 return;
559 }
560  
561 # Note: HTML::Element compatibility
562 sub delete_content
563 {
564 my $self = shift( @_ );
565 $self->children->foreach(sub
566 {
567 $_->delete;
568 });
569 $self->reset(1);
570 return( $self );
571 }
572  
573 # Note: HTML::Element compatibility
574 # Does not do anything by design
575 sub delete_ignorable_whitespace {}
576  
577 sub depth
578 {
579 my $self = shift( @_ );
580 my $n = 0;
581 my $parent = $self;
582 $n++ while( $parent = $parent->parent );
583 return( $self->new_number( $n ) );
584 }
585  
586 sub descendants
587 {
588 my $self = shift( @_ );
589 my $a = $self->new_array;
590 $self->traverse(sub
591 {
592 my $e = shift( @_ );
593 my $class = $e->class;
594 return(1) unless( $class eq 'HTML::Object::Element' );
595 $a->push( $e );
596 });
597 return( $a );
598 }
599  
600 # Note: HTML::Element compatibility
601 sub destroy { return( shift->delete( @_ ) ); }
602  
603 sub destroy_content { return( shift->delete_content( @_ ) ); }
604  
605 # Note: HTML::Element compatibility
606 sub detach
607 {
608 my $self = shift( @_ );
609 my $parent = $self->parent;
610 return if( !$parent );
611 my $id = $self->eid;
612 my $pos = $parent->children->pos( $self );
613 if( defined( $pos ) )
614 {
615 $parent->children->splice( $pos, 1 );
616 $self->parent( undef() );
617 $parent->reset(1);
618 }
619 return( $parent );
620 }
621  
622 # Note: HTML::Element compatibility
623 sub detach_content
624 {
625 my $self = shift( @_ );
626 $self->children->foreach(sub
627 {
628 shift->parent( undef() );
629 });
630 my @removed = $self->children->list;
631 $self->children->reset;
632 return( @removed );
633 }
634  
635 sub dump
636 {
637 my $self = shift( @_ );
638 my $depth = shift( @_ ) || 0;
639 my $prefix = '.' x $depth;
640 $depth++;
641 my $tag = $self->tag;
642 printf( STDOUT "${prefix} Tag '$tag' has %d children.\n", $self->children->length ) if( $self->children->length );
643 my %esc = (
644 "\a" => "\\a",
645 "\b" => "\\b",
646 "\t" => "\\t",
647 "\n" => "\\n",
648 "\f" => "\\f",
649 "\r" => "\\r",
650 "\e" => "\\e",
651 );
652 $self->children->foreach(sub
653 {
654 my $e = shift( @_ );
655 my $str = $e->original->scalar;
656 $str =~ s/([\a\b\t\n\f\r\e])/$esc{$1}/gs;
657 $str =~ s/([\0-\037])(?!\d)/sprintf('\\%o',ord($1))/eg;
658 $str =~ s/([\0-\037\177-\377])/sprintf('\\x%02X',ord($1))/eg;
659 $str =~ s/([^\040-\176])/sprintf('\\x{%X}',ord($1))/eg;
660 print( STDOUT "${prefix}. ${str}\n" );
661 $e->dump( $depth ) if( !$e->is_empty || $e->children->length );
662 });
663 return( $self );
664 }
665  
666 sub eid { return( shift->{eid} ); }
667  
668 # Returns self, but is overriden in HTML::Object::Collection
669 # See <https://api.jquery.com/end/#end>
670 sub end { return( shift( @_ ) ); }
671  
672 sub extract_links
673 {
674 my $self = shift( @_ );
675 my @tags = @_;
676 for( @tags )
677 {
678 $_ = lc( $_ );
679 }
680 my $wants = {};
681 @$wants{ @tags } = (1) x scalar( @tags );
682 my $has_expectation = scalar( keys( %$wants ) );
683 my $a = $self->new_array;
684 my $crawl;
685 my $seen = {};
686 $crawl = sub
687 {
688 my $kids = shift( @_ );
689 $kids->foreach(sub
690 {
691 my $e = shift( @_ );
692 my $def;
693 my $tag = $e->tag;
694 $def = $HTML::Object::LINK_ELEMENTS->{ "$tag" } if( exists( $HTML::Object::LINK_ELEMENTS->{ "$tag" } ) );
695 # return(1) if( !defined( $def ) );
696 # return(1) if( $has_expectation && !exists( $wants->{ "$tag" } ) );
697 if( defined( $def ) &&
698 (
699 !$has_expectation ||
700 ( $has_expectation && !exists( $wants->{ "$tag" } ) )
701 ) )
702 {
703 foreach my $attr ( @$def )
704 {
705 my $val;
706 if( $e->attributes->exists( $attr ) && length( $val = $e->attributes->get( $attr ) ) )
707 {
708 $a->push( $self->new_hash({
709 attribute => $attr,
710 element => $e,
711 tag => $tag,
712 value => $val,
713 }) );
714 }
715 }
716 }
717 my $addr = Scalar::Util::refaddr( $e );
718 if( ++$seen->{ $addr } > 1 )
719 {
720 return(1);
721 }
722 $crawl->( $e->children );
723 return(1);
724 });
725 };
726 $crawl->( $self->children );
727 return( $a );
728 }
729  
730 # Note: HTML::Element compatibility
731 # sub find { return( shift->find_by_tag_name( @_ ) ); }
732 # find() is a xpath method
733  
734 sub find_by_attribute
735 {
736 my $self = shift( @_ );
737 my( $att, $val ) = @_;
738 $att = lc( $att );
739 return( $self->error( "No attribute was provided." ) ) if( !length( $att ) );
740 my $a = $self->new_array;
741 $a->push( $self ) if( $self->attributes->exists( $att ) && $self->attributes->get( $att ) eq $val );
742 my $crawl;
743 $crawl = sub
744 {
745 my $elems = shift( @_ );
746 $elems->foreach(sub
747 {
748 my $e = shift( @_ );
749 return(1) if( $e->class ne 'HTML::Object::Element' );
750 $a->push( $e ) if( $e->attributes->exists( $att ) && $e->attributes->get( $att ) eq $val );
751 $crawl->( $e->children ) if( $e->children->length > 0 );
752 });
753 };
754 $crawl->( $self->children ) if( $self->children->length > 0 );
755 return( $a );
756 }
757  
758 sub find_by_tag_name
759 {
760 my $self = shift( @_ );
761 my @tags = @_;
762 for( @tags )
763 {
764 $_ = lc( $_ );
765 }
766 my $tags = {};
767 @$tags{ @tags } = (1) x scalar( @tags );
768 my $a = $self->new_array;
769 $a->push( $self ) if( exists( $tags->{ $self->tag } ) );
770 my $crawl;
771 $crawl = sub
772 {
773 my $elems = shift( @_ );
774 $elems->foreach(sub
775 {
776 my $e = shift( @_ );
777 # return(1) if( $e->class ne 'HTML::Object::Element' );
778 return(1) if( !$self->_is_a( $e => 'HTML::Object::Element' ) );
779 $a->push( $e ) if( exists( $tags->{ $e->tag } ) );
780 $crawl->( $e->children ) if( $e->children->length > 0 );
781 });
782 };
783 $crawl->( $self->children ) if( $self->children->length > 0 );
784 return( $a );
785 }
786  
787 sub has_children { return( shift->children->is_empty ? 0 : 1 ); }
788  
789 sub id : lvalue { return( shift->_set_get_id( @_ ) ); }
790  
791 # Note: Similar to HTML::ELement, but not quite, because we have no concept of pos(), so this just add to the stack of children
792 sub insert_element
793 {
794 my $self = shift( @_ );
795 my $e = shift( @_ ) || return( $self->error( "No html element was provided to insert." ) );
796 return( $self->error( "Element provided (", overload::StrVal( $e ), ") is not an object." ) ) if( !$self->_is_object( $e ) );
797 return( $self->error( "Element provided (", overload::StrVal( $e ), ") is not an HTML::Object::Element." ) ) if( !$e->isa( 'HTML::Object::Element' ) );
798 $self->push_content( $e );
799 $self->reset(1);
800 return( $e );
801 }
802  
803 # Used to store arbitrarily data for internal purpose
804 sub internal { return( shift->reset(@_)->_set_get_hash_as_mix_object( '_internal', @_ ) ); }
805  
806 sub is_closed { return( shift->reset(@_)->_set_get_boolean( 'is_closed', @_ ) ); }
807  
808 # Note: Different from HTML::Element in that this is a flag derived from the dictionary. To get the equivalent, one must use has_children()
809 sub is_empty { return( shift->reset(@_)->_set_get_boolean( 'is_empty', @_ ) ); }
810  
811 sub is_valid_attribute { return( $_[1] =~ /^$ATTRIBUTE_NAME_RE$/ ? 1 : 0 ); }
812  
813 sub is_void { return( shift->reset(@_)->is_empty( @_ ) ); }
814  
815 # Note: Compatibility with HTML::Element
816 sub left
817 {
818 my $self = shift( @_ );
819 my $offset = @_ ? int( shift( @_ ) ) : 0;
820 my $pos = $self->pos;
821 # We return empty if we could not find our object within our parent's children; or
822 # the requested offset position is higher than the position of our object
823 return( $self->new_array ) if( !defined( $pos ) || $offset > $pos );
824 my $kids = $self->parent->children;
825 # I am my parent's only child; no need to bother
826 return( $self->new_array ) if( $kids->length == 1 );
827 # We use position as offset length which will put us right before our own element
828 return( $kids->offset( $offset, ( $pos - $offset ) ) );
829 }
830  
831 sub line { return( shift->_set_get_number_as_object( 'line', @_ ) ); }
832  
833 # Note: HTML::Element compatibility
834 sub lineage
835 {
836 my $self = shift( @_ );
837 my $parent = $self;
838 my $lineage = $self->new_array;
839 while( $parent = $parent->parent )
840 {
841 $lineage->push( $parent );
842 }
843 return( $lineage );
844 }
845  
846 sub lineage_tag_names
847 {
848 my $self = shift( @_ );
849 my $a = $self->new_array;
850 my $parent = $self;
851 while( $parent = $parent->parent )
852 {
853 $a->push( $parent->tag->scalar );
854 }
855 return( $a );
856 }
857  
858 sub look
859 {
860 my $self = shift( @_ );
861 my $opts = {};
862 $opts = pop( @_ ) if( ref( $_[-1] ) eq 'HASH' );
863 my $p = [];
864 for( my $i = 0; $i < scalar( @_ ); )
865 {
866 if( ref( $_[$i] ) )
867 {
868 return( $self->error( "Reference provided (", overload::StrVal( $_[$i] ), "), but the only reference I accept is code reference." ) ) if( ref( $_[$i] ) ne 'CODE' );
869 push( @$p, $_[ $i++ ] );
870 }
871 else
872 {
873 push( @$p, {
874 key => $_[$i],
875 val => $_[$i + 1],
876 });
877 $i += 2;
878 }
879 }
880 my $a = $self->new_array;
881 my( $check_elem, $crawl_down );
882 $check_elem = sub
883 {
884 my $e = shift( @_ );
885 my $def = shift( @_ );
886 my $attr = $e->attributes;
887 # Assume ok, then check otherwise
888 my $ok = 1;
889 foreach my $this ( @$p )
890 {
891 if( ref( $this ) eq 'CODE' )
892 {
893 local $_ = $e;
894 my $rc = $this->( $e );
895 $ok = 0, last if( !$rc );
896 }
897 else
898 {
899 if( $this->{key} eq '_tag' )
900 {
901 if( ref( $this->{val} ) eq 'Regexp' )
902 {
903 $ok = 0, last if( $e->tag !~ /$this->{val}/ );
904 }
905 else
906 {
907 $ok = 0, last if( $e->tag ne $this->{val} );
908 }
909 }
910 elsif( !$attr->exists( $this->{key} ) )
911 {
912 if( !defined( $this->{val} ) )
913 {
914 # Good to go; the user searches for an attribute with an undefined value
915 # in other term, the user wants an element whose attribute does not exist
916 }
917 else
918 {
919 $ok = 0, last;
920 }
921 }
922 else
923 {
924 my $val = $attr->get( $this->{key} );
925 if( defined( $val ) )
926 {
927 if( ref( $this->{val} ) eq 'Regexp' )
928 {
929 $ok = 0, last if( $val !~ /$this->{val}/ );
930 }
931 elsif( (
932 ref( $this->{val} ) &&
933 ref( $this->{val} ) ne ref( $val )
934 ) ||
935 (
936 ( !ref( $val ) || overload::Method( $val. '""' ) ) &&
937 lc( "$val" ) ne lc( "$this->{val}" )
938 ) )
939 {
940 $ok = 0, last;
941 }
942 }
943 else
944 {
945 $ok = 0, last if( defined( $this->{val} ) );
946 }
947 }
948 }
949 }
950  
951 # We passed all checks, no checking our children
952 $a->push( $e ) if( $ok );
953 # Stop here since we reached the maximum number of matches
954 return if( CORE::exists( $opts->{max_match} ) && $a->length >= $opts->{max_match} );
955 # Don't go down or up further if we reached the maximum level
956 return(1) if( CORE::exists( $opts->{max_level} ) && ( $def->{level} + 1 ) > $opts->{max_level} );
957 $def->{level}++;
958 if( $opts->{direction} eq 'down' )
959 {
960 $crawl_down->( $e->children, $def ) if( $e->children->length > 0 );
961 }
962 elsif( $opts->{direction} eq 'up' )
963 {
964 $check_elem->( $e->parent ) if( $e->parent );
965 }
966 $def->{level}--;
967 return(1);
968 };
969  
970 $crawl_down = sub
971 {
972 my $kids = shift( @_ );
973 my $def = shift( @_ );
974 # $kids->foreach( $check_elem );
975 $kids->foreach(sub
976 {
977 $check_elem->( $_, $def );
978 });
979 };
980  
981 my $def = { level => 0 };
982 $check_elem->( $self, $def );
983 # return( $a->length > 0 ? $a : '' );
984 return( $a );
985 }
986  
987 sub look_down
988 {
989 my $self = shift( @_ );
990 my $opts = {};
991 $opts = pop( @_ ) if( ref( $_[-1] ) eq 'HASH' );
992 $opts->{direction} = 'down';
993 return( $self->look( @_, $opts ) );
994 }
995  
996 sub look_up
997 {
998 my $self = shift( @_ );
999 my $opts = {};
1000 $opts = pop( @_ ) if( ref( $_[-1] ) eq 'HASH' );
1001 $opts->{direction} = 'up';
1002 return( $self->look( @_, $opts ) );
1003 }
1004  
1005 sub looks_like_html { return( $_[1] =~ /$LOOK_LIKE_HTML/ ? 1 : 0 ); }
1006  
1007 # sub looks_like_it_has_html { return( $_[1] =~ /$LOOK_LIKE_IT_HAS_HTML/ ? 1 : 0 ); }
1008 sub looks_like_it_has_html
1009 {
1010 my $self = shift( @_ );
1011 return( $_[0] =~ /$LOOK_LIKE_IT_HAS_HTML/ ? 1 : 0 );
1012 }
1013  
1014 sub modified { return( shift->_set_get_boolean( 'modified', @_ ) ); }
1015  
1016 sub new_attribute
1017 {
1018 my $self = shift( @_ );
1019 $self->_load_class( 'HTML::Object::Attribute' ) || return( $self->pass_error );
1020 my $att = HTML::Object::Attribute->new( @_ ) ||
1021 return( $self->pass_error( HTML::Object::Attribute->error ) );
1022 return( $att );
1023 }
1024  
1025 sub new_closing
1026 {
1027 my $self = shift( @_ );
1028 $self->_load_class( 'HTML::Object::Closing' ) || return( $self->pass_error );
1029 my $e = HTML::Object::Closing->new( @_ ) ||
1030 return( $self->pass_error( HTML::Object::Closing->error ) );
1031 return( $e );
1032 }
1033  
1034 sub new_document
1035 {
1036 my $self = shift( @_ );
1037 $self->_load_class( 'HTML::Object::Document' ) || return( $self->pass_error );
1038 my $e = HTML::Object::Document->new( debug => $self->debug ) ||
1039 return( $self->pass_error( HTML::Object::Document->error ) );
1040 return( $e );
1041 }
1042  
1043 sub new_element
1044 {
1045 my $self = shift( @_ );
1046 my $tag = shift( @_ ) || return( $self->error( "No tag was provided to create an element." ) );
1047 my $dict = HTML::Object->get_definition( $tag ) || return( $self->pass_error( HTML::Object->error ) );
1048 my $e = HTML::Object::Element->new({
1049 is_empty => $dict->{is_empty},
1050 tag => $dict->{tag},
1051 debug => $self->debug,
1052 }) || return( $self->pass_error( HTML::Object::Element->error ) );
1053 return( $e );
1054 }
1055  
1056 sub new_from_lol
1057 {
1058 my $self = shift( @_ );
1059 my $a = $self->new_array;
1060 my @args = @_;
1061 my $crawl;
1062 $crawl = sub
1063 {
1064 my $ref = shift( @_ );
1065 my $parent;
1066 $parent = shift( @_ ) if( scalar( @_ ) );
1067 my $elem;
1068 foreach my $this ( @$ref )
1069 {
1070 if( $self->_is_array( $this ) )
1071 {
1072 my $e = $crawl->( $this, ( $elem // $parent ) ) || return;
1073 if( defined( $elem ) || defined( $parent ) )
1074 {
1075 $e->parent( $elem // $parent );
1076 ( $elem // $parent )->children->push( $e );
1077 }
1078 }
1079 elsif( $self->_is_hash( $this ) )
1080 {
1081 return( $self->error( "Hash of attributes set found before tag name definition" ) ) if( !defined( $elem ) );
1082 $elem->attributes( $this );
1083 }
1084 elsif( $self->_is_object( $this ) && $this->isa( 'HTML::Object::Element' ) )
1085 {
1086 my $custodian = ( $elem // $parent );
1087 my $e = $this->parent ? $this->clone : $this;
1088 return( $self->error( "Found an element object \"", $e->tag, "\" to add to the tree, but no parent was provided nor any element was initiated yet." ) ) if( !defined( $custodian ) );
1089 $e->parent( $custodian );
1090 $custodian->children->push( $e );
1091 }
1092 else
1093 {
1094 return( $self->error( "Found an object ($this), but I do not know what to do with it." ) ) if( $self->_is_object( $this ) && ( !overload::Overloaded( $this ) || ( overload::Overloaded( $this ) && !overload::Method( $this => '""' ) ) ) );
1095 # This is the element tag name
1096 if( !defined( $elem ) && "$this" =~ /^\w+$/ )
1097 {
1098 $elem = $self->new_element( "$this" ) || return;
1099 if( defined( $parent ) )
1100 {
1101 $elem->parent( $parent );
1102 $parent->children->push( $elem );
1103 }
1104 }
1105 # Text node added as a child
1106 else
1107 {
1108 my $custodian = ( $elem // $parent );
1109 return( $self->error( "Found a text to add to the tree, but no parent was provided nor any element was initiated yet." ) ) if( !defined( $custodian ) );
1110 my $t = $self->new_text( "$this" ) || return;
1111 $t->parent( $custodian );
1112 $custodian->children->push( $t );
1113 }
1114 }
1115 }
1116 return( $elem );
1117 };
1118  
1119 foreach my $this ( @args )
1120 {
1121 return( $self->error( "I was expecting an array reference, but instead got '$this'." ) ) if( !$self->_is_array( $this ) );
1122 # There are more than one elements provided in this array definition, i.e. multiple html tags at the top level
1123 # so we create a special document html element to contain them
1124 if( scalar( @$this ) > 0 )
1125 {
1126 my $doc = $self->new_document || return;
1127 $crawl->( $this => $doc ) || return;
1128 $a->push( $doc );
1129 }
1130 else
1131 {
1132 my $e = $crawl->( $this ) || return;
1133 $a->push( $e );
1134 }
1135 }
1136 return( $a );
1137 }
1138  
1139 sub new_parser
1140 {
1141 my $self = shift( @_ );
1142 $self->_load_class( 'HTML::Object' ) || return( $self->pass_error );
1143 my $p = HTML::Object->new( debug => $self->debug ) ||
1144 return( $self->pass_error( HTML::Object->error ) );
1145 return( $p );
1146 }
1147  
1148 sub new_text
1149 {
1150 my $self = shift( @_ );
1151 my $p = {};
1152 if( scalar( @_ ) == 1 && ref( $_[0] ) eq 'HASH' )
1153 {
1154 $p = shift( @_ );
1155 }
1156 else
1157 {
1158 $p->{value} = join( '', @_ );
1159 }
1160 $p->{debug} = $self->debug;
1161 $self->_load_class( 'HTML::Object::Text' ) || return( $self->pass_error );
1162 my $e = HTML::Object::Text->new( $p ) ||
1163 return( $self->pass_error( HTML::Object::Text->error ) );
1164 return( $e );
1165 }
1166  
1167 # TODO: next()
1168  
1169 # Note: HTML::Element compatibility
1170 sub normalize_content
1171 {
1172 my $self = shift( @_ );
1173 my $children = $self->children;
1174 my $new = $self->new_array;
1175 my $prev;
1176 $children->foreach(sub
1177 {
1178 if( ( defined( $_ ) && $self->_is_a( $_ => 'HTML::Object::Text' ) && defined( $prev ) && $self->_is_a( $prev => 'HTML::Object::Text' ) ) ||
1179 ( defined( $_ ) && $self->_is_a( $_ => 'HTML::Object::Space' ) && defined( $prev ) && $self->_is_a( $prev => 'HTML::Object::Space' ) ) )
1180 {
1181 $prev->value->append( $_->value );
1182 return(1);
1183 }
1184 $prev = $_;
1185 $new->push( $_ );
1186 });
1187 $self->children( $new );
1188 return( $self );
1189 }
1190  
1191 sub offset { return( shift->reset(@_)->_set_get_number_as_object( 'offset', @_ ) ); }
1192  
1193 sub original { return( shift->_set_get_scalar_as_object( 'original', @_ ) ); }
1194  
1195 sub parent { return( shift->_set_get_object_without_init({
1196 field => 'parent',
1197 weaken => 1,
1198 }, 'HTML::Object::Element', @_ ) ); }
1199  
1200 # Note: Different from the one in HTML::Element
1201 sub pos
1202 {
1203 my $self = shift( @_ );
1204 my $parent = $self->parent;
1205 return( $self->new_null ) if( !$parent );
1206 my $kids = $parent->children;
1207 #my $id = $self->eid;
1208 #my( $pos ) = grep{ $kids->[$_]->eid eq $id } 0..$#$kids;
1209 #return( $pos );
1210 return( $kids->pos( $self ) );
1211 }
1212  
1213 sub pindex { return( shift->pos( @_ ) ); }
1214  
1215 # TODO: previous()
1216  
1217 # Note: HTML::Element compatibility
1218 sub postinsert
1219 {
1220 my $self = shift( @_ );
1221 my $parent = $self->parent;
1222 return( $self->error( "Element has no parent." ) ) if( !$parent );
1223 my $pos = $parent->children->pos( $self );
1224 return( $self->error( "Element is not found among parent's children elements." ) ) if( !defined( $pos ) );
1225 my $new = $self->_get_elements_list( @_ ) || return( $self->pass_error );
1226 $new->foreach(sub
1227 {
1228 $_->detach if( $_->parent );
1229 $_->parent( $parent );
1230 });
1231 $parent->children->splice( $pos + 1, 0, $new->list );
1232 $parent->reset(1);
1233 return( $self );
1234 }
1235  
1236 # Note: HTML::Element compatibility
1237 sub preinsert
1238 {
1239 my $self = shift( @_ );
1240 my $parent = $self->parent;
1241 return( $self->error( "Element has no parent." ) ) if( !$parent );
1242 my $pos = $parent->children->pos( $self );
1243 return( $self->error( "Element is not found among parent's children elements." ) ) if( !defined( $pos ) );
1244 my $new = $self->_get_elements_list( @_ ) || return( $self->pass_error );
1245 $new->foreach(sub
1246 {
1247 $_->detach if( $_->parent );
1248 $_->parent( $parent );
1249 });
1250 $parent->children->splice( $pos, 0, $new->list );
1251 $parent->reset(1);
1252 return( $self );
1253 }
1254  
1255 # Note: HTML::Element compatibility
1256 sub push_content
1257 {
1258 my $self = shift( @_ );
1259 return( $self ) unless( @_ );
1260 my $children = $self->children;
1261 my $new = $self->_get_elements_list( @_ ) || return( $self->pass_error );
1262 $new->foreach(sub
1263 {
1264 $_->detach if( $_->parent );
1265 $_->parent( $self );
1266 $children->push( $_ );
1267 });
1268 $self->reset(1);
1269 return( $self );
1270 }
1271  
1272 # Note: HTML::Element compatibility
1273 sub replace_with
1274 {
1275 my $self = shift( @_ );
1276 my $parent = $self->parent;
1277 return( $self->error( "Element has no parent." ) ) if( !$parent );
1278 my $pos = $parent->children->pos( $self );
1279 return( $self->error( "Element is not found among parent's children elements." ) ) if( !defined( $pos ) );
1280 my $new = $self->_get_elements_list( @_ ) || return( $self->pass_error );
1281 $new->foreach(sub
1282 {
1283 $_->detach if( $_->parent );
1284 $_->parent( $parent );
1285 });
1286 $parent->children->splice( $pos, 1, $new->list );
1287 $parent->reset(1);
1288 return( $self );
1289 }
1290  
1291 sub replace_with_content
1292 {
1293 my $self = shift( @_ );
1294 my $parent = $self->parent;
1295 my $children = $self->children;
1296 return( $self->error( "This element has no parent." ) ) if( !$parent );
1297 my $pos = $parent->children->pos( $self );
1298 return( $self->error( "Unable to find the current element among its parent's children." ) ) if( !defined( $pos ) );
1299 $children->foreach(sub
1300 {
1301 $_->parent( $parent );
1302 });
1303 $parent->splice( $pos, 1, $children->list );
1304 $self->parent( undef() );
1305 $parent->reset(1);
1306 return( $self );
1307 }
1308  
1309 sub reset
1310 {
1311 my $self = shift( @_ );
1312 if( !CORE::length( $self->{_reset} ) && scalar( @_ ) )
1313 {
1314 $self->{_reset} = scalar( @_ );
1315 if( my $parent = $self->parent )
1316 {
1317 $parent->reset(1);
1318 }
1319 }
1320 return( $self );
1321 }
1322  
1323 # Note: HTML::Element compatibility
1324 sub right
1325 {
1326 my $self = shift( @_ );
1327 my $parent = $self->parent;
1328 return( $self->new_null ) if( !$parent );
1329 my $kids = $parent->children;
1330 my $pos = $self->pos;
1331 my $offset = @_ ? int( shift( @_ ) ) : $kids->size;
1332 return( $self->new_array ) if( !defined( $pos ) || $offset < $pos );
1333 return( $self->new_array ) if( $kids->length == 1 );
1334 # my $results = $kids->offset( $pos + 1, ( $offset - $pos ) );
1335 return( $kids->offset( $pos + 1, ( $offset - $pos ) ) );
1336 }
1337  
1338 # Note: HTML::Element compatibility
1339 sub root
1340 {
1341 my $self = shift( @_ );
1342 my $root = $self;
1343 my $parent;
1344 while( $parent = $root->parent )
1345 {
1346 $root = $parent;
1347 }
1348 # Typically a HTML::Object::Document
1349 return( $root );
1350 }
1351  
1352 sub same_as
1353 {
1354 my $self = shift( @_ );
1355 my $elem = shift( @_ ) || return( $self->error( "No element object was provided to compare against." ) );
1356 return( $self->error( "Element provided (", overload::StrVal( $elem ), ") is not an object." ) ) if( !$self->_is_object( $elem ) );
1357 return( $self->error( "Element provided (", overload::StrVal( $elem ), ") is not an HTML::Object::Element object." ) ) if( !$elem->isa( 'HTML::Object::Element' ) );
1358 my $my_attr = $self->attributes->keys->sort;
1359 my $her_attr = $elem->attributes->keys->sort;
1360 return(0) unless( $my_attr eq $her_attr );
1361 $my_attr->foreach(sub
1362 {
1363 return(0) if( $self->attributes->get( $_ ) ne $elem->attributes->get( $_ ) );
1364 });
1365 return(0) if( $self->children->length != $elem->children->length );
1366 my $her_kids = $elem->children;
1367 $self->children->for(sub
1368 {
1369 my( $i, $e ) = @_;
1370 return(0) if( !$e->same_as( $her_kids->[$i] ) );
1371 });
1372 return(1);
1373 }
1374  
1375 sub set_checksum
1376 {
1377 my $self = shift( @_ );
1378 my $tag = $self->_tag;
1379 my $a = $self->new_array( [$tag] );
1380 $self->attributes_sequence->foreach(sub
1381 {
1382 my $attr = shift( @_ );
1383 $a->push( $self->attributes->get( $attr ) );
1384 });
1385 return( $self->_get_md5_hash( $a->join( ';' )->scalar ) );
1386 }
1387  
1388 # Note: HTML::Element compatibility
1389 sub splice_content
1390 {
1391 my $self = shift( @_ );
1392 my $offset = shift( @_ );
1393 my $length = shift( @_ );
1394 return( $self ) unless( @_ );
1395 return( $self->error( "Offset value provided '$offset' is not an integer." ) ) if( !$self->_is_integer( $offset ) );
1396 return( $self->error( "Length value provided '$length' is not an integer." ) ) if( !$self->_is_integer( $length ) );
1397 my $children = $self->children;
1398 my $new = $self->_get_elements_list( @_ ) || return( $self->pass_error );
1399 $new->foreach(sub
1400 {
1401 $_->detach if( $_->parent );
1402 $_->parent( $self );
1403 });
1404 $children->splice( $offset, $length, $new->list );
1405 $self->reset(1);
1406 return( $self );
1407 }
1408  
1409 sub tag { return( shift->reset(@_)->_set_get_scalar_as_object( 'tag', @_ ) ); }
1410  
1411 # Note: HTML::Element compatibility
1412 sub traverse
1413 {
1414 my $self = shift( @_ );
1415 my $code = shift( @_ ) || return( $self->error( "No code provided to traverse the html tree." ) );
1416 return( $self->error( "The argument provided (", overload::StrVal( $code ), ") is not an anonymous subroutine." ) ) if( ref( $code ) ne 'CODE' );
1417 my $opts = $self->_get_args_as_hash( @_ );
1418 $opts->{bottom_up} //= 0;
1419 my $seen = {};
1420 my $crawl;
1421 $crawl = sub
1422 {
1423 my $e = shift( @_ );
1424 my $addr = Scalar::Util::refaddr( $e );
1425 # Duplicate
1426 return if( ++$seen->{ $addr } > 1 );
1427 local $_ = $e;
1428 $code->( $e ) unless( $opts->{bottom_up} );
1429 $e->children->foreach(sub
1430 {
1431 $crawl->( $_[0] );
1432 });
1433 $code->( $e ) if( $opts->{bottom_up} );
1434 };
1435 $crawl->( $self );
1436 return( $self );
1437 }
1438  
1439 # Note: HTML::Element compatibility
1440 sub unshift_content
1441 {
1442 my $self = shift( @_ );
1443 return( $self ) unless( @_ );
1444 my $children = $self->children;
1445 my $new = $self->_get_elements_list( @_ ) || return( $self->pass_error );
1446 $new->foreach(sub
1447 {
1448 $_->parent( $self );
1449 });
1450 $children->splice( 0, 0, $new->list );
1451 $self->reset(1);
1452 return( $self );
1453 }
1454  
1455 # called on a parent, with a child as second argument and its rank as third
1456 # returns the child if it is already an element, or
1457 # a new HTML::Object::Text element if it is a plain string
1458 sub _child_as_object
1459 {
1460 my( $self, $elt_or_text, $rank ) = @_;
1461 return unless( defined( $elt_or_text ) );
1462 if( !ref( $elt_or_text ) )
1463 {
1464 require HTML::Object::Text;
1465 # $elt_or_text is a string, turn it into a TextNode object
1466 $elt_or_text = HTML::Object::Text->new(
1467 parent => $self,
1468 value => $elt_or_text,
1469 );
1470 }
1471 warn( "rank is a ", ref( $rank ), " elt_or_text is a ", ref( $elt_or_text ) ) if( ref( $rank ) && !$self->_is_a( $rank, 'Module::Generic::Number' ) );
1472 # used for sorting
1473 $elt_or_text->rank( $rank );
1474 return( $elt_or_text );
1475 }
1476  
1477 sub _generate_uuid
1478 {
1479 return( lc( Data::UUID->new->create_str ) );
1480 }
1481  
1482 sub _get_elements_list
1483 {
1484 my $self = shift( @_ );
1485 my $new = $self->new_array;
1486 my $seen = {};
1487 my $prev;
1488 my $self_addr = Scalar::Util::refaddr( $self );
1489 my $parent_addr;
1490 my $parent = $self->parent;
1491 $parent_addr = Scalar::Util::refaddr( $parent ) if( defined( $parent ) );
1492 for( @_ )
1493 {
1494 return( $self->error( "Replacement element is not an HTML::Object::Element" ) ) if( !$self->_is_a( $_ => 'HTML::Object::Element' ) );
1495 my $addr = Scalar::Util::refaddr( $_ );
1496 if( ++$seen->{ $addr } > 1 )
1497 {
1498 warn( "Warnings only: found duplicate element with tag '" . $_->tag . "' provided in replace_with()\n" ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
1499 next;
1500 }
1501 return( $self->error( "Replacement list contains a copy of target!" ) ) if( $self_addr eq $addr );
1502 return( $self->error( "Cannot replace an item with its parent!" ) ) if( defined( $parent_addr ) && $addr eq $parent_addr );
1503 if( ( $_->isa( 'HTML::Object::Text' ) && defined( $prev ) && $prev->isa( 'HTML::Object::Text' ) ) ||
1504 ( $_->isa( 'HTML::Object::Space' ) && defined( $prev ) && $prev->isa( 'HTML::Object::Space' ) ) )
1505 {
1506 $prev->value->append( $_->value );
1507 next;
1508 }
1509 $new->push( $_ );
1510 $prev = $_;
1511 }
1512 return( $new );
1513 }
1514  
1515 # Used by after, append, before
1516 sub _get_from_list_of_elements_or_html
1517 {
1518 my $self = shift( @_ );
1519 my $list = $self->new_array;
1520 my $prev;
1521 foreach my $this ( @_ )
1522 {
1523 if( $self->_is_a( $this => 'HTML::Object::Element' ) )
1524 {
1525 if( $self->_is_a( $this => 'HTML::Object::DOM::DocumentFragment' ) )
1526 {
1527 my $clone = $this->children->clone;
1528 $list->push( $clone->list );
1529 $this->children->reset;
1530 undef( $prev );
1531 }
1532 elsif( $self->_is_a( $this => 'HTML::Object::Text' ) )
1533 {
1534 if( defined( $prev ) && $self->_is_a( $prev => 'HTML::Object::Text' ) )
1535 {
1536 $prev->value->append( $this->value );
1537 }
1538 else
1539 {
1540 my $clone = $this->clone;
1541 $list->push( $clone );
1542 $prev = $clone;
1543 }
1544 }
1545 else
1546 {
1547 my $clone = $this->clone;
1548 $list->push( $clone );
1549 # $list->push( $clone->close_tag ) if( $clone->close_tag );
1550 undef( $prev );
1551 }
1552 }
1553 else
1554 {
1555 if( ref( $this ) && ( !$self->_is_object( $this ) || ( $self->_is_object( $this ) && !overload::Method( $this, '""' ) ) ) )
1556 {
1557 return( $self->error( "I was expecting some HTML data, but got '", overload::StrVal( $this ), "'" ) );
1558 }
1559  
1560 # if( "$this" =~ /$LOOK_LIKE_HTML/ )
1561 # LOOK_LIKE_HTML check for html tag starting at the beginning of the string
1562 # LOOK_LIKE_IT_HAS_HTML checks for tag anywhere
1563 if( "$this" =~ /$LOOK_LIKE_IT_HAS_HTML/ )
1564 {
1565 my $p = $self->new_parser( debug => 4 );
1566 my $res = $p->parse_data( "$this" ) ||
1567 return( $self->error( "Error while parsing html data provided: ", $p->error ) );
1568 $list->push( $res->children->list ) if( !$res->children->is_empty );
1569 }
1570 # Maybe just some text provided, and in that case, the parser would return nothing unfortunately
1571 else
1572 {
1573 if( defined( $prev ) && $self->_is_a( $prev => 'HTML::Object::Text' ) )
1574 {
1575 $prev->value->append( "$this" );
1576 }
1577 else
1578 {
1579 my $e = $self->new_text({ value => "$this" });
1580 $list->push( $e );
1581 $prev = $e;
1582 }
1583 }
1584 }
1585 }
1586 return( $list );
1587 }
1588  
1589 sub _get_md5_hash
1590 {
1591 my $self = shift( @_ );
1592 my $data = shift( @_ );
1593 return( $self->error( "No data was provided to compute a md5 hash." ) ) if( !defined( $data ) || !length( "$data" ) );
1594 # try-catch
1595 local $@;
1596 my $rv = eval
1597 {
1598 return( Digest::MD5::md5_hex( Encode::encode( 'utf8', $data, Encode::FB_CROAK ) ) );
1599 };
1600 if( $@ )
1601 {
1602 return( $self->error( "An error occurred while calculating the md5 hash for tag \"", $self->tag, "\": $@" ) );
1603 }
1604 return( $rv );
1605 }
1606  
1607 # For other modules to use
1608 sub _is_reset { return( CORE::length( shift->{_reset} ) ); }
1609  
1610 # For other modules to use
1611 sub _remove_reset { return( CORE::delete( shift->{_reset} ) ); }
1612  
1613 # Method shared with HTML::Object::XQuery
1614 sub _set_get_id : lvalue { return( shift->_set_get_callback({
1615 get => sub
1616 {
1617 my $self = shift( @_ );
1618 my $id = $self->new_scalar( $self->attributes->get( 'id' ) );
1619 return( $id );
1620 },
1621 set => sub
1622 {
1623 my $self = shift( @_ );
1624 my $id = shift( @_ );
1625 if( !defined( $id ) || !CORE::length( $id ) )
1626 {
1627 if( $self->attributes->exists( 'id' ) )
1628 {
1629 $self->attributes->delete( 'id' );
1630 $self->attributes_sequence->remove( 'id' );
1631 $self->reset(1);
1632 return(1);
1633 }
1634 return(0);
1635 }
1636 else
1637 {
1638 $self->attributes->set( id => $id );
1639 $self->reset(1);
1640 return(1);
1641 }
1642 }
1643 }, @_ ) ); }
1644  
1645 sub _same_as
1646 {
1647 my $self = shift( @_ );
1648 my $this = shift( @_ );
1649 return(0) if( !defined( $this ) || ( defined( $this ) && !$self->_is_a( $this, 'HTML::Object::Element' ) ) );
1650 return( $self->eid CORE::eq $this->eid ? 1 : 0 );
1651 }
1652  
1653 # Used to register callbacks for some properties like rel, sizes, controlslist that we trigger and that update the attribute's HTML::Object::TokenList
1654 sub _set_get_internal_attribute_callback
1655 {
1656 my $self = shift( @_ );
1657 $self->{_internal_attribute_callbacks} = {} if( ref( $self->{_internal_attribute_callbacks} ) ne 'HASH' );
1658 my $ref = $self->{_internal_attribute_callbacks};
1659 # get mode
1660 if( scalar( @_ ) == 1 )
1661 {
1662 my $attr = shift( @_ );
1663 return( $ref->{ $attr } );
1664 }
1665 elsif( scalar( @_ ) )
1666 {
1667 return( $self->error( "Odd number of parameters for attribute callback assignment." ) ) if( ( @_ % 2 ) );
1668 for( my $i = 0; $i < scalar( @_ ); $i += 2 )
1669 {
1670 $ref->{ $_[ $i ] } = $_[ $i + 1 ];
1671 }
1672 return( $self );
1673 }
1674 return;
1675 }
1676  
1677 # A private method for internal use when the tag method has been overriden for example as it is the case in HTML::Object::XQuery
1678 sub _tag { return( shift->reset(@_)->_set_get_scalar_as_object( 'tag', @_ ) ); }
1679  
1680 1;
1681 # NOTE: POD
1682 __END__