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

filter: Statementstmt 0.0% 0 / 2543 Branchbran 0.0% 0 / 1384 Conditioncond 0.0% 0 / 846 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 155 Podpod 0.0% 0 / 123 totaltotal 0.0% 0 / 5051 CC 693 SCAR 69.2
CC
693
Cov
0%
ajax
7310.0
load
992.0
_before_after
992.0
CRAP 1011.9
1 ##----------------------------------------------------------------------------
2 ## HTML Object - ~/lib/HTML/Object/XQuery.pm
3 ## Version v0.4.0
4 ## Copyright(c) 2024 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2021/05/01
7 ## Modified 2024/04/27
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::XQuery;
15 BEGIN
16 {
17 use strict;
18 use warnings;
19 warnings::register_categories( 'HTML::Object' );
20 use parent qw( HTML::Object::DOM );
21 use vars qw( @EXPORT $DEBUG $VERSION );
22 our @EXPORT = qw( xq );
23 our $DEBUG = 0;
24 our $VERSION = 'v0.4.0';
25 };
26  
27 use strict;
28 use warnings;
29  
30 {
31 no warnings 'once';
32 *xq = \&HTML::Object::DOM::Element::xq;
33 }
34  
35 # NOTE: DateTimeFormat class
36 # package
37 # DateTimeFormat;
38 # BEGIN
39 # {
40 # use strict;
41 # use warnings;
42 # use parent qw( HTML::Object::DateTime::Format );
43 # };
44 #
45 # use strict;
46 # use warnings;
47  
48 # NOTE: xQuery class
49 package xQuery;
50 BEGIN
51 {
52 use strict;
53 use warnings;
54 use parent qw( Module::Generic );
55 };
56 use strict;
57 use warnings;
58  
59 {
60 no warnings 'once';
61 # NOTE: clearQueue
62 *clearQueue = \&HTML::Object::DOM::Element::clearQueue;
63 # NOTE: contains
64 *contains = \&HTML::Object::DOM::Element::contains;
65 }
66  
67 sub data
68 {
69 my $self = shift( @_ );
70 my $elem = shift( @_ ) || return( $self->error( "No element was provided to set/get data on it." ) );
71 return( $self->error( "Element value provided is not an HTML::Object::DOM::Element" ) ) if( !$self->_is_a( $elem => 'HTML::Object::DOM::Element' ) );
72 my $rv = $elem->data( @_ );
73 return( $self->pass_error( $elem->error ) ) if( !defined( $rv ) && $elem->error );
74 return( $rv );
75 }
76  
77 {
78 no warnings 'once';
79 # NOTE: dequeue
80 *dequeue = \&HTML::Object::DOM::Element::dequeue;
81 }
82  
83 sub each
84 {
85 my $self = shift( @_ );
86 my( $data, $cb ) = @_;
87 my $obj;
88 if( $self->_is_array( $data ) )
89 {
90 $obj = $self->new_array( $data );
91 }
92 elsif( $self->_is_hash( $data ) )
93 {
94 $obj = $self->new_hash( $data );
95 }
96 else
97 {
98 return( $self->error( "Unsupported data type (", overload::StrVal( $data // 'undef' ), ")" ) );
99 }
100 return( $self->error( "Callback value provided is not a code reference." ) ) if( !$self->_is_code( $cb ) );
101 return( $obj->each($cb) );
102 }
103  
104 sub extend
105 {
106 my $self = shift( @_ );
107 my $deep = 0;
108 if( scalar( @_ ) && !$self->_is_hash( $_[0] ) )
109 {
110 my $bool = shift( @_ );
111 $deep = $bool ? 1 : 0;
112 }
113 # Clean up the arguments
114 my @args = ();
115 for( my $i = 0; $i < scalar( @_ ); $i++ )
116 {
117 if( $self->_is_hash( $_[$i] ) )
118 {
119 push( @args, $_[$i] );
120 }
121 }
122 return( {} ) if( !scalar( @args ) );
123 return( { map( %$_, @args ) } ) unless( $deep );
124 # Credits: Hash::Merge::Simple
125 my $merge;
126 $merge = sub
127 {
128 my( $left, @right ) = @_;
129 return( $left ) unless( @right );
130 return( $merge->( $left, $merge->( @right ) ) ) if( @right > 1 );
131 my( $right ) = @right;
132 my $merged = { %$left };
133 foreach my $key ( keys( %$right ) )
134 {
135 my( $hr, $hl ) = map{ ref( $_->{ $key } ) eq 'HASH' } $right, $left;
136 # Both hash have the same key pointing to an hash
137 if( $hr and $hl )
138 {
139 $merged->{ $key } = $merge->( $left->{ $key }, $right->{ $key } );
140 }
141 else
142 {
143 $merged->{ $key } = $right->{ $key };
144 }
145 }
146 return( $merged );
147 };
148 return( $merge->( @args ) );
149 }
150  
151 sub grep
152 {
153 my $self = shift( @_ );
154 my( $ref, $cb, $invert ) = @_;
155 return( $self->error( "Value provided is not an array reference." ) ) if( !$self->_is_array( $ref ) );
156 return( $self->error( "Callback value provided is not a code reference." ) ) if( !$self->_is_code( $cb ) );
157 $invert //= 0;
158 $ref = $self->new_array( $ref );
159 return( $ref->grep( $cb, $invert ) );
160 }
161  
162 sub inArray
163 {
164 my $self = shift( @_ );
165 my( $val, $array, $fromIndex ) = @_;
166 return( $self->error( "Array value provided is not an array." ) ) if( !$self->_is_array( $array ) );
167 return( $self->error( "fromIndex value provided is not an integer." ) ) if( defined( $fromIndex ) && !$self->_is_integer( $fromIndex ) );
168 $fromIndex //= 0;
169 my $isRe = ( ref( $val ) eq 'Regexp' ? 1 : 0 );
170 for( my $i = 0; $i < scalar( @$array ); $i++ )
171 {
172 next unless( $i >= $fromIndex );
173 if( $isRe )
174 {
175 return( $i ) if( $array->[$i] =~ /$val/ );
176 }
177 else
178 {
179 return( $i ) if( $array->[$i] eq $val );
180 }
181 }
182 return(-1);
183 }
184  
185 sub isArray { return( shift->_is_array( @_ ) ); }
186  
187 sub isEmptyObject
188 {
189 my $self = shift( @_ );
190 my $this = shift( @_ );
191 return(0) if( !$self->_is_hash( $this, 'strict' ) );
192 return( scalar( keys( %$this ) ) ? 0 : 1 );
193 }
194  
195 sub isFunction
196 {
197 my $self = shift( @_ );
198 my $this = shift( @_ );
199 return(0) if( $self->_is_empty( $this ) );
200 return(1) if( $self->_is_code( $this ) );
201 my $pkg = caller;
202 if( $self->_has_symbol( $pkg => "\&${this}" ) &&
203 defined( &{"${pkg}\::${this}"} ) )
204 {
205 return(1);
206 }
207 return(0);
208 }
209  
210 sub isNumeric { return( shift->_look_like_number( @_ ) ); }
211  
212 sub isPlainObject { return( shift->_is_hash( shift( @_ ), 'strict' ) ); }
213  
214 sub isWindow { return( shift->_is_a( shift( @_ ) => 'HTML::Object::DOM::Window' ) ); }
215  
216 sub makeArray
217 {
218 my $self = shift( @_ );
219 my $ref = shift( @_ );
220 if( $self->_is_a( $ref => 'HTML::Object::Collection' ) )
221 {
222 $ref = $ref->children;
223 }
224 return( $self->error( "Value provided is not an array reference or an array object." ) ) if( !$self->_is_array( $ref ) );
225 my $new = [];
226 @$new = @$ref;
227 return( $new );
228 }
229  
230 sub map
231 {
232 my $self = shift( @_ );
233 my $ref = shift( @_ ) || return( $self->error( "No data was provided." ) );
234 my $code = shift( @_ ) || return( $self->error( "No code reference was provided." ) );
235 return( $self->error( "I was expecting a code reference, but instead I was provided with this: \"", overload::StrVal( $code ), "\"." ) ) if( ref( $code ) ne 'CODE' );
236 my $type;
237 if( $self->_is_array( $ref ) )
238 {
239 $type = 'array';
240 }
241 elsif( $self->_is_hash( $ref => 'strict' ) )
242 {
243 $type = 'hash';
244 }
245 my $new = $self->new_array;
246 local $@;
247 if( defined( $type ) )
248 {
249 my $each = sub
250 {
251 if( $type eq 'hash' )
252 {
253 return( CORE::each( %$ref ) );
254 }
255 else
256 {
257 return( CORE::each( @$ref ) );
258 }
259 };
260  
261 # We use a callback, because perl does not accept: each( $type eq 'array' ? @$ref : %$ref )
262 while( my( $key, $value ) = $each->() )
263 {
264 # try-catch
265 my @rv = eval
266 {
267 $code->( $value, $key );
268 };
269 if( $@ )
270 {
271 warn( "An error occured while executing callback for key ${key}: $@" ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
272 next;
273 }
274 # User returned an empty array or undef
275 if( !scalar( @rv ) || ( scalar( @rv ) == 1 && !defined( $rv[0] ) ) )
276 {
277 next;
278 }
279 if( scalar( @rv ) == 1 )
280 {
281 # User returned an array reference, such as:
282 # my @rv = $.map( $array, sub{ return( [1, 2, 3] ) } );
283 if( $self->_is_array( $rv[0] ) )
284 {
285 $new->push( @{$rv[0]} );
286 }
287 else
288 {
289 # warn( "Warning only: value returned from the \$.map callback for key ${key} did not return either undef or an array reference: ", join( ', ', map( overload::StrVal( $_ // 'undef' ), @rv ) ) ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
290 $new->push( $rv[0] );
291 }
292 }
293 # User returned an array of more than 1 item, such as:
294 # my @rv = $.map( $array, sub{ return( 1, 2, 3 ) } );
295 else
296 {
297 $new->push( @rv );
298 }
299 }
300 return( $new );
301 }
302 else
303 {
304 return( $self->error( "The data provided is neither an array reference, an array object or an hash reference." ) );
305 }
306 }
307  
308 sub merge
309 {
310 my $self = shift( @_ );
311 my( $first, $second ) = @_;
312 return( $self->error( "First value provided is not an array reference." ) ) if( !$self->_is_array( $first ) );
313 return( $self->error( "Second value provided is not an array reference." ) ) if( !$self->_is_array( $second ) );
314 CORE::push( @$first, @$second );
315 return( $first );
316 }
317  
318 sub noop { return }
319  
320 sub now
321 {
322 my $self = shift( @_ );
323 $self->_load_class( 'DateTime' ) || return( $self->pass_error );
324 $self->_load_class( 'DateTime::Format::Strptime' ) || return( $self->pass_error );
325 my $fmt = DateTime::Format::Strptime->new(
326 pattern => '%s',
327 );
328 my $dt = DateTime->now(
329 formatter => $fmt,
330 );
331 return( $dt );
332 }
333  
334 sub parseHTML
335 {
336 my( $self, $str ) = @_;
337 my $res = $self->new_array;
338 return( $res ) if( $self->_is_empty( $str ) );
339 my $parser = HTML::Object::DOM->new( debug => $self->debug );
340 my $doc = $parser->parse_data( "$str" ) ||
341 return( $self->pass_error( $parser->error ) );
342 $res->push( $doc->children->list );
343 return( $res );
344 }
345  
346 sub parseJSON
347 {
348 my( $self, $str ) = @_;
349 return( $self->error( "No JSON data was provided to parse" ) ) if( $self->_is_empty( $str ) );
350 my $j = $self->new_json( allow_tags => 0 );
351 # try-catch
352 local $@;
353 my $rv = eval
354 {
355 return( $j->decode( "$str" ) );
356 };
357 if( $@ )
358 {
359 return( $self->error( "An error occurred while parsing ", CORE::length( "$str" ), " bytes of JSON data: $@" ) );
360 }
361 return( $rv );
362 }
363  
364 sub parseXML
365 {
366 my( $self, $str ) = @_;
367 return( $self->error( "No XML data was provided to parse" ) ) if( $self->_is_empty( $str ) );
368 if( !$self->_load_class( 'XML::LibXML' ) )
369 {
370 return( $self->pass_error );
371 }
372 # try-catch
373 local $@;
374 my $doc = eval
375 {
376 XML::LibXML->load_xml( string => $str );
377 };
378 if( $@ )
379 {
380 return( $self->error( "Error while parsing XML data with XML::LibXML: $@" ) );
381 }
382 return( $doc );
383 }
384  
385 # NOTE: $.proxy() is deprecated
386 # <https://api.jquery.com/jQuery.proxy/>
387  
388 # NOTE: $.queue() is unsupported as it has no meaning under perl
389 # <https://api.jquery.com/jQuery.queue/>
390  
391 sub removeData
392 {
393 my $self = shift( @_ );
394 my $elem = shift( @_ ) || return( $self->error( "No element was provided." ) );
395 return( $self->error( "Element object provided is not an HTML::Object::DOM::Element" ) ) if( !$self->_is_a( $elem => 'HTML::Object::DOM::Element' ) );
396 $elem->removeData( scalar( @_ ) ? @_ : () );
397 return( $self->pass_error( $elem->error ) ) if( $elem->error );
398 return;
399 }
400  
401 # NOTE: support() is not supported
402 # <https://api.jquery.com/jQuery.support/>
403  
404 sub trim
405 {
406 my $self = shift( @_ );
407 my $this = shift( @_ );
408 return( $this ) if( $self->_is_empty( $this ) );
409 if( ref( $this ) &&
410 !$self->_can_overload( $this => '""' ) )
411 {
412 return( $self->error( "Value provided is not a string nor a stringifyable object." ) );
413 }
414 my $str = "$this";
415 $str =~ s/^[[:blank:]\h\v]+|[[:blank:]\h\v]+$//gs;
416 return( $str );
417 }
418  
419 sub type
420 {
421 my $self = shift( @_ );
422 my $this = shift( @_ );
423 if( !defined( $this ) )
424 {
425 return( 'undef' );
426 }
427 elsif( $self->_is_hash( $this => 'strict' ) )
428 {
429 return( 'hash' );
430 }
431 elsif( $self->_is_array( $this ) )
432 {
433 return( 'array' );
434 }
435 elsif( $self->_is_a( $this => [qw( DateTime Module::Generic::DateTime )] ) )
436 {
437 return( 'date' );
438 }
439 elsif( $self->_is_a( $this => [qw( Module::Generic::Boolean JSON::PP::Boolean )] ) )
440 {
441 return( 'boolean' );
442 }
443 elsif( $self->_is_a( $this => 'Regexp' ) )
444 {
445 return( 'regexp' );
446 }
447 elsif( $self->_is_a( $this => [qw( Module::Generic::Exception Error Throwable::Error )] ) )
448 {
449 return( 'error' );
450 }
451 elsif( $self->_is_number( $this ) )
452 {
453 return( 'number' );
454 }
455 elsif( $self->_look_like_number( $this ) )
456 {
457 return( 'number' );
458 }
459 else
460 {
461 return( 'string' );
462 }
463 }
464  
465 sub unique
466 {
467 my $self = shift( @_ );
468 my $arr = shift( @_ ) || return( $self->error( "No array was provided to make unique." ) );
469 return( $self->error( "Value provided is not an array reference or an array object." ) ) if( !$self->_is_array( $arr ) );
470 my $res = $self->new_array( $arr )->unique;
471 return( $res );
472 }
473  
474 sub uniqueSort
475 {
476 my $self = shift( @_ );
477 my $new = $self->unique( @_ ) || return( $self->pass_error );
478 return( $new ) if( $new->is_empty );
479 my $root = $new->first->getRootNode;
480 # <https://stackoverflow.com/questions/63575333/javascript-replacement-of-sourceindex-in-chromium-browsers>
481 # <https://developer.mozilla.org/en-US/docs/Web/API/Document/all>
482 # <https://johnresig.com/blog/comparing-document-position/#postcomment>
483 # Compare Position - MIT Licensed, John Resig
484 # function comparePosition(a, b)
485 # {
486 # return a.compareDocumentPosition
487 # ? a.compareDocumentPosition(b)
488 # : a.contains
489 # ? ( a != b && a.contains(b) && 16 ) +
490 # ( a != b && b.contains(a) && 8 ) +
491 # ( a.sourceIndex >= 0 && b.sourceIndex >= 0
492 # ? ( a.sourceIndex < b.sourceIndex && 4 ) + ( a.sourceIndex > b.sourceIndex && 2 )
493 # : 1
494 # ) + 0
495 # : 0;
496 # }
497 my $all = $root->querySelectorAll('*');
498 for( my $i = 0; $i < scalar( @$all ); $i++ )
499 {
500 my $e = $all->[$i];
501 $e->sourceIndex( $i );
502 }
503 $new = $new->sort(sub
504 {
505 my( $a, $b ) = @_;
506 return(
507 $a->can( 'compareDocumentPosition' )
508 ? $a->compareDocumentPosition( $b )
509 : $a->can( 'contains' )
510 ? ( $a !=$ b && $a->contains($b) && 16 ) +
511 ( $a != $b && $b->contains($a) && 8 ) +
512 ( ( $a->sourceIndex // -1 ) >= 0 && ( $b->sourceIndex // -1 ) >= 0
513 ? ( $a->sourceIndex < $b->sourceIndex && 4 ) + ( $a->sourceIndex > $b->sourceIndex && 2 )
514 : 1
515 ) + 0
516 : 0
517 );
518 });
519 return( $new );
520 }
521  
522 # NOTE: HTML::Object::DOM::Element class
523 package HTML::Object::DOM::Element;
524 BEGIN
525 {
526 use strict;
527 use warnings;
528 use vars qw( $XP $LOOK_LIKE_HTML $VERSION );
529 use CSS::Object;
530 use HTML::Object::Collection;
531 use HTML::Object::DOM::Attribute;
532 use HTML::Object::DOM::Boolean;
533 use HTML::Object::DOM::Document;
534 use HTML::Object::DOM::Number;
535 use HTML::Object::DOM::Root;
536 # use HTML::Object::DOM::Text;
537 use HTML::Selector::XPath 0.20 qw( selector_to_xpath );
538 use List::Util ();
539 # use Promise::XS ();
540 # use Promise::Me;
541 use HTML::Object::XPath;
542 use overload (
543 'eq' => \&_same_as,
544 '==' => \&_same_as,
545 fallback => 1,
546 );
547 our $XP;
548 # As perl jQuery documentation
549 our $LOOK_LIKE_HTML = qr/^[[:blank:]\h\v]*\<\w+.*?\>/;
550 };
551  
552 use strict;
553 use warnings;
554 no warnings 'redefine';
555  
556 # Takes a selector (e.g. '.some-class'); or
557 # a collection (i.e. one or more elements resulting from a find or equivalent query); or
558 # "HTML fragment to add to the set of matched elements."; or
559 # a selector and a context (i.e. an element object); or
560 # a element object
561 # $self->add( $selector );
562 # $self->add( $elements );
563 # $self->add( $html );
564 # $self->add( $selector, $context );
565 sub add
566 {
567 my $self = shift( @_ );
568 my( $this, $context ) = @_;
569 # Compliant with what jQuery does, i.e. when no argument is provide this just returns a collection of the collecting object
570 my $collection = $self->new_collection( end => $self );
571 # if( $self->isa_element && !$self->isa_collection )
572 if( $self->isa_collection )
573 {
574 $collection->children( $self->children );
575 }
576 elsif( $self->isa_element )
577 {
578 $collection->children->push( $self );
579 }
580  
581 if( !defined( $this ) )
582 {
583 return( $collection )
584 }
585 # e.g.: $( "p" ).add( "div" )
586 # $( "li" ).add( "<p id='new'>new paragraph</p>" )
587 # elsif( !ref( $this ) || ( ref( $this ) && overload::Overloaded( $this ) && overload::Method( $this, '""' ) ) )
588 elsif( !ref( $this ) || overload::Method( $this, '""' ) )
589 {
590 # https://api.jquery.com/Types/#htmlString
591 # $( "li" ).add( "<p id='new'>new paragraph</p>" )
592 if( "$this" =~ /$LOOK_LIKE_HTML/ )
593 {
594 my $p = $self->new_parser;
595 $this = $p->parse_data( "$this" ) || return( $self->pass_error( $p->error ) );
596 }
597 # selector
598 # $( "p" ).add( "div" )
599 else
600 {
601 # $self->add( $selector, $context );
602 if( defined( $context ) )
603 {
604 return( $self->error( "A context has been provided, but it is not an HTML::Object::DOM::Element." ) ) if( !$self->_is_object( $context ) || !$context->isa( 'HTML::Object::DOM::Element' ) );
605 $this = $context->find( "$this" ) || return( $self->pass_error( $context->error ) );
606 }
607 # $self->add( $selector );
608 elsif( defined( $HTML::Object::DOM::GLOBAL_DOM ) )
609 {
610 my $selector = "$this";
611 $this = $HTML::Object::DOM::GLOBAL_DOM->find( "$selector" ) || return( $self->pass_error( $HTML::Object::DOM::GLOBAL_DOM->error ) );
612 }
613 else
614 {
615 return( $self->error( "You need to provide some context to the selector by supplying an HTML::Object::DOM::Element object." ) );
616 }
617 }
618 }
619 # Some array or hash ref provided maybe ?
620 elsif( !$self->_is_object( $this ) )
621 {
622 return( $self->error( "I was expecting an HTML::Object::DOM::Element, an HTML::Object::Collection, an html string or a selector., but instead I got '$this'." ) );
623 }
624  
625 # We now have either an element object or a collection of them
626 # We return a new collection either way
627 if( $self->isa_collection( $this ) )
628 {
629 $collection->children->merge( $this->children->unique );
630 }
631 elsif( $this->isa( 'HTML::Object::DOM::Element' ) )
632 {
633 $collection->children->push( $this );
634 }
635 else
636 {
637 return( $self->error( "An object of class \"", ref( $this ), "\" was provided, but I do not know what to do with it. I was expecting an HTML::Object::DOM::Element, or an HTML::Object::Collection." ) );
638 }
639 return( $collection );
640 }
641  
642 # To make it look like really like jQuery
643 sub addClass
644 {
645 my( $self, $class ) = @_;
646 return( $self->error( "I received a reference to add as a class, but was expecting a string or a code reference." ) ) if( ref( $class ) && ref( $class ) ne 'CODE' && !( overload::Overloaded( $class ) && overload::Method( $class, '""' ) ) );
647 $class = "${class}" unless( ref( $class ) CORE::eq 'CODE' );
648 my $set_attr;
649 $set_attr = sub
650 {
651 my( $i, $e ) = @_;
652 my $v = $e->attr( 'class' ) // '';
653 local $_ = $e;
654 my $classes = ref( $class ) CORE::eq 'CODE'
655 ? $class->({ element => $e, pos => $i, value => $v })
656 : $class;
657 my $cl_ref = $self->new_array(
658 $self->_is_array( $classes )
659 ? $classes
660 : CORE::length( "$classes" )
661 ? [split( /[[:blank:]\h]+/, "${classes}" )]
662 : []
663 );
664 my $curr;
665 if( CORE::length( "${v}" ) )
666 {
667 $curr = $self->_is_a( $v, 'Module::Generic::Array' ) ? $v : $self->new_array( [split( /[[:blank:]\h]+/, $v )] );
668 my $new = $self->new_array;
669 $cl_ref->foreach(sub
670 {
671 # <http://www.w3.org/TR/CSS21/grammar.html#scanner>
672 # <https://stackoverflow.com/questions/448981/which-characters-are-valid-in-css-class-names-selectors#449000>
673 $new->push( $_ ) if( !$curr->exists( $_ ) );
674 });
675 $curr->push( $new->list ) if( $new->length );
676 }
677 else
678 {
679 $curr = $cl_ref;
680 }
681 $e->attr( class => $curr->join( ' ' )->scalar );
682 $e->reset(1);
683 };
684  
685 if( $self->isa_collection )
686 {
687 $self->children->for( $set_attr );
688 }
689 else
690 {
691 my $v = $self->attr( 'class' ) // '';
692 # Here 0 is a dummy number to satisfy the code ref required by for()
693 $set_attr->( 0, $self );
694 }
695 }
696  
697 # <https://api.jquery.com/after/>
698 sub after { return( shift->_before_after( @_, { action => 'after' } ) ); }
699  
700 sub ajax
701 {
702 my $self = shift( @_ );
703 my $url = shift( @_ ) ||
704 return( $self->error( "No URL was provided." ) );
705 my $opts = $self->_get_args_as_hash( @_ );
706 $opts->{async} //= 1;
707 $opts->{cache} = 0;
708 $opts->{processData} //= 1;
709 $opts->{debug} //= 0;
710 $self->_load_class( 'HTTP::Promise', { version => 'v0.5.0' } ) ||
711 return( $self->pass_error );
712 $self->_load_class( 'HTTP::Promise::Request' ) ||
713 return( $self->pass_error );
714 $self->_load_class( 'URI', { version => '5.21' } ) ||
715 return( $self->pass_error );
716 if( !$self->_is_empty( $opts->{url} ) )
717 {
718 $url = $opts->{url};
719 }
720 my $uri = URI->new( "$url" );
721 # Contextual URL that requires a base URL.
722 # We check for documentURI of the root element, if any
723 my( $doc_root, $doc_uri );
724 if( ( substr( $url, 0, 1 ) eq '/' ||
725 substr( $url, 0, 2 ) eq './' ||
726 substr( $url, 0, 3 ) eq '../' ) &&
727 ( $doc_root = $self->getRootNode ) &&
728 $doc_root->isa( 'HTML::Object::DOM::Document' ) &&
729 ( $doc_uri = $doc_root->documentURI ) )
730 {
731 $uri = $doc_uri->clone;
732 $uri->path( $url );
733 }
734 # !contents
735 # !context
736 # converters
737 # !crossDomain
738 # NOTE dataType
739 my $dataType;
740 $dataType = $opts->{dataType} if( !$self->_is_empty( $opts->{dataType} ) );
741 # NOTE error
742 my $error;
743 if( $self->_is_code( $opts->{error} ) )
744 {
745 $error = [$opts->{error}];
746 }
747 elsif( $self->_is_array( $opts->{error} ) )
748 {
749 for( my $i = 0; $i < scalar( @{$opts->{error}} ); $i++ )
750 {
751 my $this = $opts->{error}->[$i];
752 if( !$self->_is_code( $opts->{error}->[$i] ) )
753 {
754 return( $self->error( "Value provided at offset $i with the 'error' argument to ajax method, is not a code reference." ) );
755 }
756 }
757 $error = $opts->{error};
758 }
759 # NOTE headers
760 my $headers = ( ( exists( $opts->{headers} ) && ref( $opts->{headers} // '' ) eq 'HASH' ) ? $opts->{headers} : {} );
761 unless( exists( $headers->{X_Requested_With} ) || exists( $headers->{ 'X-Requested-With' } ) )
762 {
763 $headers->{X_Requested_With} = 'XMLHttpRequest';
764 }
765 # !global
766 # !isLocal
767 # !jsonp
768 # !jsonpCallback
769 my $params =
770 {
771 use_promise => ( $opts->{async} ? 1 : 0 ),
772 # NOTE timeout
773 ( $self->_is_integer( $opts->{timeout} ) ? ( timeout => $opts->{timeout} ) : () ),
774 ( ( $self->_is_integer( $opts->{debug} ) && $opts->{debug} ) ? ( debug => $opts->{debug} ) : () ),
775 };
776 # NOTE accepts
777 if( !$self->_is_empty( $opts->{accepts} ) )
778 {
779 $headers->{accept} = $opts->{accepts};
780 }
781 elsif( !$self->_is_empty( $opts->{accept} ) )
782 {
783 $headers->{accept} = $opts->{accept};
784 }
785 # NOTE contentType
786 if( !$self->_is_empty( $opts->{contentType} ) )
787 {
788 $headers->{Content_Type} = $opts->{contentType};
789 }
790 # NOTE ifModified
791 if( exists( $opts->{ifModified} ) &&
792 ref( $opts->{ifModified} ) eq 'HASH' )
793 {
794 my $ifmod = $opts->{ifModified};
795 if( exists( $ifmod->{since} ) &&
796 defined( $ifmod->{since} ) &&
797 CORE::length( $ifmod->{since} ) )
798 {
799 my $dt;
800 if( $ifmod->{since} =~ /^\d{10}$/ )
801 {
802 # try-catch
803 local $@;
804 $dt = eval
805 {
806 DateTime->from_epoch( epoch => $ifmod->{since} );
807 };
808 if( $@ )
809 {
810 return( $self->error( "Error with the timestamp provided for the option ifModified: $@" ) );
811 }
812 }
813 elsif( $self->_is_a( $ifmod->{since} => [qw( DateTime Module::Generic::DateTime )] ) )
814 {
815 $dt = $ifmod->{since};
816 }
817 else
818 {
819 return( $self->error( "Unsupported value provided to option ifModified->since: '", ( $ifmod->{since} // 'undef' ), "'" ) );
820 }
821  
822 $self->_load_class( 'DateTime::Format::Strptime' ) ||
823 return( $self->pass_error );
824 $dt->set_time_zone( 'GMT' );
825 my $fmt = DateTime::Format::Strptime->new(
826 pattern => '%a, %d %b %Y %H:%M:%S GMT',
827 locale => 'en_GB',
828 time_zone => 'GMT',
829 );
830 $dt->set_formatter( $fmt );
831 $headers->{If_Modified_Since} = $dt;
832 }
833 if( exists( $ifmod->{etag} ) &&
834 defined( $ifmod->{etag} ) &&
835 CORE::length( $ifmod->{etag} ) )
836 {
837 if( $ifmod->{etag} =~ /^[\w\-]+$/ )
838 {
839 $headers->{If_None_Match} = '"' . $ifmod->{etag} . '"';
840 }
841 # Useless to use the weak prefix since If-None-Match only uses the weak algorithm
842 elsif( $ifmod->{etag} =~ m,W/"^[\w\-]+"$, )
843 {
844 $headers->{If_None_Match} = $ifmod->{etag};
845 }
846 else
847 {
848 return( $self->error( "The etag provided for the option ifModified->etag contains illegal characters." ) );
849 }
850 }
851 }
852 # !isLocal
853 # !jsonp
854 # NOTE method, type
855 my $method = 'get';
856 $opts->{method} = $opts->{type} if( !$self->_is_empty( $opts->{method} ) && !$self->_is_empty( $opts->{type} ) );
857 if( exists( $opts->{method} ) &&
858 defined( $opts->{method} ) &&
859 CORE::length( $opts->{method} // '' ) )
860 {
861 if( $opts->{method} =~ /^(get|head|options|patch|post|put)$/i )
862 {
863 $method = lc( $1 );
864 }
865 else
866 {
867 return( $self->error( "Unsupported HTTP method '$opts->{method}'" ) );
868 }
869 }
870 # NOTE data, processData
871 my $data;
872 if( $opts->{data} )
873 {
874 if( $opts->{processData} )
875 {
876 $headers->{Content} = $data;
877 }
878 else
879 {
880 $headers->{Content} = "$data";
881 }
882 }
883 else
884 {
885 }
886  
887 # NOTE mimeType
888 if( !$self->_is_empty( $opts->{mimeType} ) )
889 {
890 $headers->{Content_Type} = $opts->{mimeType};
891 }
892 # !scriptAttrs
893 # !scriptCharset
894 # NOTE statusCode
895 my $statusCode;
896 if( exists( $opts->{statusCode} ) &&
897 defined( $opts->{statusCode} ) &&
898 ref( $opts->{statusCode} // '' ) eq 'HASH' )
899 {
900 foreach my $c ( sort( keys( %{$opts->{statusCode}} ) ) )
901 {
902 if( !defined( $c ) || !CORE::length( "$c" // '' ) )
903 {
904 return( $self->error( "The code value provided in the option statusCode is empty!" ) );
905 }
906 elsif( "$c" !~ /^\d{3}$/ )
907 {
908 return( $self->error( "The code value provided (${c}) is invalid. It should be a 3 digits code, such as 200" ) );
909 }
910  
911 my $code_ref = $opts->{statusCode}->{ $c };
912 if( !$self->_is_code( $code_ref ) )
913 {
914 return( $self->error( "The value provided for status code '${c}' is not a code reference." ) );
915 }
916 }
917 $statusCode = $opts->{statusCode};
918 }
919 # NOTE success
920 my $success;
921 if( exists( $opts->{success} ) )
922 {
923 if( $self->_is_code( $opts->{success} ) )
924 {
925 $success = $opts->{success};
926 }
927 else
928 {
929 return( $self->error( "The success callback provided is not a code reference." ) );
930 }
931 }
932 # !traditional
933  
934 my $http = HTTP::Promise->new( %$params ) ||
935 return( $self->pass_error( HTTP::Promise->error ) );
936 my $req = $http->prepare( $method => $uri, %$headers ) ||
937 return( $self->pass_error( $http->error ) );
938 if( exists( $opts->{xhr} ) && defined( $opts->{xhr} ) )
939 {
940 if( $self->_is_code( $opts->{xhr} ) )
941 {
942 my $code_ref = $opts->{xhr};
943 # try-catch
944 local $@;
945 my $this = eval
946 {
947 $code_ref->( $req );
948 };
949 if( $@ )
950 {
951 return( $self->error( "An error occurred while calling the callback code reference for xhr: $@" ) ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
952 }
953 if( $self->_is_a( $this => 'HTTP::Promise::Request' ) )
954 {
955 $req = $this;
956 }
957 else
958 {
959 return( $self->error( "The value returned by the callback (", overload::StrVal( $this // '' ), ") is not an HTTP::Promise::Request object." ) );
960 }
961 }
962 else
963 {
964 return( $self->error( "The value provided for the xhr callback is not a code reference." ) );
965 }
966 }
967  
968 # NOTE password & username
969 if( !$self->_is_empty( $opts->{password} ) ||
970 !$self->_is_empty( $opts->{username} ) )
971 {
972 $req->headers->authorization_basic( ( $opts->{username} // '' ), ( $opts->{password} // '' ) );
973 }
974 # NOTE beforeSend
975 my $beforeSend = ( $self->_is_code( $opts->{beforeSend} ) ? $opts->{beforeSend} : sub{ $_[0] } );
976 my $complete;
977 if( $self->_is_code( $opts->{complete} ) )
978 {
979 $complete = [$opts->{complete}];
980 }
981 elsif( $self->_is_array( $opts->{complete} ) )
982 {
983 for( my $i = 0; $i < scalar( @{$opts->{complete}} ); $i++ )
984 {
985 my $this = $opts->{complete}->[$i];
986 if( !$self->_is_code( $opts->{complete}->[$i] ) )
987 {
988 return( $self->error( "Value provided at offset $i with the 'complete' argument to ajax method, is not a code reference." ) );
989 }
990 }
991 $complete = $opts->{complete};
992 }
993  
994 # NOTE dataFilter
995 my $dataFilter = ( $self->_is_code( $opts->{dataFilter} ) ? $opts->{dataFilter} : sub{ $_[0] } );
996 my $code2status = sub
997 {
998 my $resp = shift( @_ );
999 my $code = $resp->code;
1000 if( $code == 200 )
1001 {
1002 return( 'success' );
1003 }
1004 elsif( $code == 204 )
1005 {
1006 return( 'nocontent' );
1007 }
1008 elsif( $code == 304 )
1009 {
1010 return( 'notmodified' );
1011 }
1012 elsif( $code == 408 )
1013 {
1014 return( 'timeout' );
1015 }
1016 elsif( $code >= 400 && $code <= 599 )
1017 {
1018 return( 'error' );
1019 }
1020 else
1021 {
1022 return( 'success' );
1023 }
1024 };
1025  
1026 my $process = sub
1027 {
1028 my $resp = shift( @_ );
1029 my( $resolve, $reject ) = @_;
1030 my $status = $code2status->( $resp );
1031 my $code = $resp->code;
1032 # TODO: converters
1033 my $content = $resp->decoded_content;
1034 $content = $dataFilter->( $content );
1035 my $decoded;
1036 unless( defined( $dataType ) )
1037 {
1038 my $type = $resp->headers->type;
1039 if( defined( $type ) )
1040 {
1041 if( $type =~ m,^application/json,i )
1042 {
1043 $dataType = 'json';
1044 }
1045 elsif( $type =~ m,^text/html,i )
1046 {
1047 $dataType = 'html';
1048 }
1049 elsif( $type =~ m,^text/xml,i )
1050 {
1051 $dataType = 'xml';
1052 }
1053 elsif( $type =~ m,^text/plain,i )
1054 {
1055 $dataType = 'text';
1056 }
1057 else
1058 {
1059 $dataType = 'application/octet-stream';
1060 }
1061 }
1062 }
1063  
1064 if( defined( $dataType ) )
1065 {
1066 if( ( $dataType eq 'json' ||
1067 $dataType eq 'jsonp' ) &&
1068 defined( $content ) )
1069 {
1070 my $j = $self->new_json->relaxed->utf8;
1071 # try-catch
1072 local $@;
1073 $decoded = eval
1074 {
1075 $j->decode( "$content" );
1076 };
1077 if( $@ )
1078 {
1079 $self->error( "Error decoding ", CORE::length( $content ), " bytes of JSON data: $@" );
1080 if( defined( $reject ) )
1081 {
1082 return({ error => $self->error });
1083 }
1084 else
1085 {
1086 return( $self->pass_error );
1087 }
1088 }
1089 else
1090 {
1091 # $resolve->( $decoded );
1092 $content = $decoded;
1093 }
1094 }
1095 }
1096 else
1097 {
1098 # Hmm, dataType is still undefined
1099 }
1100  
1101 if( defined( $statusCode ) )
1102 {
1103 my $code_ref = $statusCode->{ $code };
1104 # try-catch
1105 local $@;
1106 eval
1107 {
1108 $code_ref->( $content, $status, $resp, $http );
1109 };
1110 if( $@ )
1111 {
1112 warn( "Error calling statusCode callback for code '${code}': $@" ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
1113 }
1114 }
1115  
1116 if( defined( $complete ) )
1117 {
1118 foreach my $coderef ( @$complete )
1119 {
1120 $coderef->( $resp, $status, $http );
1121 }
1122 }
1123  
1124 if( defined( $success ) )
1125 {
1126 # try-catch
1127 local $@;
1128 eval
1129 {
1130 $success->( $content, $status, $resp, $http );
1131 };
1132 if( $@ )
1133 {
1134 warn( "Error calling success callback: $@" ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
1135 }
1136 }
1137 if( defined( $error ) && ( $code >= 400 && $code < 600 ) )
1138 {
1139 my $status = $resp->status;
1140 for( my $i = 0; $i < scalar( @$error ); $i++ )
1141 {
1142 my $code_ref = $error->[$i];
1143 # try-catch
1144 local $@;
1145 eval
1146 {
1147 # No exception object, because this is just a regular HTTP error
1148 $code_ref->( $req, $status );
1149 };
1150 if( $@ )
1151 {
1152 warn( "An error occurred while calling the error callback at offset $i: $@" ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
1153 }
1154 }
1155 }
1156 return({
1157 content => $content,
1158 status => $status,
1159 resp => $resp,
1160 http => $http,
1161 });
1162 };
1163  
1164 if( $params->{use_promise} )
1165 {
1166 my $p;
1167 $p = Promise::Me->new(sub
1168 {
1169 my( $resolve_main, $reject_main ) = @$_;
1170 # NOTE: Process beforeSend for asynchronous process
1171 my $this = $beforeSend->( $req );
1172 if( !defined( $this ) || !CORE::length( $this // '' ) )
1173 {
1174 return( $resolve_main->( '', 'abort', undef, $http ) );
1175 }
1176 elsif( !$self->_is_a( $this => 'HTTP::Promise::Request' ) )
1177 {
1178 $self->error( "Value returned by the beforeSend callback is not an HTTP::Promise::Request object." );
1179 my $err = $self->error;
1180 return( $reject_main->( $err ) );
1181 }
1182 $req = $this;
1183 my $prom = $http->request( $req,
1184 ( defined( $opts->{promise_debug} ) ? ( promise_debug => $opts->{promise_debug} ) : () ),
1185 )->then(sub
1186 {
1187 my( $resolve, $reject ) = @$_;
1188 my $resp = shift( @_ );
1189 if( !$resp )
1190 {
1191 return( $reject_main->( $http->error ) );
1192 }
1193 my $res = $process->( $resp, $resolve_main, $reject_main );
1194 if( $res->{error} )
1195 {
1196 return( $reject_main->( $res->{error} ) );
1197 }
1198 return( $resolve_main->( @$res{qw( content status resp http )} ) );
1199 })->catch(sub
1200 {
1201 my $err = shift( @_ );
1202 if( defined( $error ) )
1203 {
1204 my $status = 'error';
1205 for( my $i = 0; $i < scalar( @$error ); $i++ )
1206 {
1207 my $code_ref = $error->[$i];
1208 # try-catch
1209 local $@;
1210 eval
1211 {
1212 $code_ref->( $req, $status, $err );
1213 };
1214 if( $@ )
1215 {
1216 warn( "An error occurred while calling the error callback at offset $i: $@" ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
1217 }
1218 }
1219 }
1220 return( $reject_main->( $err ) );
1221 });
1222 return( $reject_main->( $http->error ) ) if( !$prom );
1223 # return(1);
1224 return( $prom );
1225 },
1226 {
1227 ( defined( $opts->{promise_debug} ) ? ( debug => $opts->{promise_debug} ) : () ),
1228 });
1229 return( $p );
1230 }
1231 # No promise
1232 else
1233 {
1234 # NOTE: Process beforeSend for synchronous process
1235 my $this = $beforeSend->( $req );
1236 if( !defined( $this ) || !CORE::length( $this // '' ) )
1237 {
1238 return( '', 'abort', undef, $http );
1239 }
1240 elsif( !$self->_is_a( $this => 'HTTP::Promise::Request' ) )
1241 {
1242 return( $self->error( "Value returned by the beforeSend callback is not an HTTP::Promise::Request object." ) );
1243 }
1244 $req = $this;
1245 my $resp = $http->request( $req );
1246 my $res = $process->( $resp );
1247 return( $self->pass_error ) if( $res->{error} );
1248 return( @$res{qw( content status resp http )} );
1249 }
1250 }
1251  
1252 # Takes html string (start with <tag...), text object (HTML::Object::DOM::Text), array or element object
1253 # or alternatively a code reference that returns the above
1254 # <https://api.jquery.com/append/>
1255 sub append { return( shift->_append_prepend( @_, { action => 'append' } ) ); }
1256  
1257 sub appendTo { return( shift->_append_prepend_to( @_, { action => 'append' } ) ); }
1258  
1259 # $e->attr( attribute );
1260 # $collection->attribute( attribute );
1261 # $e->attr( attribute1 => value1, attribute2 => value2 );
1262 # $collection->attr( attribute1 => value1, attribute2 => value2 );
1263 # $e->attr( attribute1 => $sub_routine1, attribute2 => $string );
1264 # $collection->attr( attribute1 => $sub_routine1, attribute2 => $string );
1265 sub attr
1266 {
1267 my $self = shift( @_ );
1268 my @classes = @_;
1269 return if( !scalar( @classes ) );
1270 if( scalar( @classes ) > 1 )
1271 {
1272 my $ref = {};
1273 %$ref = @classes;
1274 my $set_attributes;
1275 $set_attributes = sub
1276 {
1277 my $e = shift( @_ );
1278 while( my( $a, $v ) = each( %$ref ) )
1279 {
1280 local $_ = $e;
1281 my $val = ref( $v ) CORE::eq 'CODE'
1282 ? $v->({ element => $e, attribute => $a, current => $e->attributes->get( $a ) })
1283 : $v;
1284 return( $self->error( "I was expecting a string value for the attribute \"${a}\", but instead got \"", overload::StrVal( $val ), "\"." ) ) if( ref( $val ) && !( overload::Overloaded( $val ) && overload::Method( $val, '""' ) ) );
1285 if( defined( $val ) )
1286 {
1287 $val = "$val";
1288 $val =~ s/^[[:blank:]\h]+|[[:blank:]\h]+$//g;
1289 $e->attributes->set( $a => $val );
1290 }
1291 else
1292 {
1293 $e->attributes->delete( $a );
1294 }
1295 }
1296 return(1);
1297 };
1298  
1299 if( $self->isa_collection )
1300 {
1301 $self->children->foreach(sub
1302 {
1303 my $e = shift( @_ );
1304 $e->reset(1);
1305 # $e->attributes->merge( $ref );
1306 $set_attributes->( $e ) || return( $self->pass_error );
1307 });
1308 }
1309 else
1310 {
1311 $self->reset(1);
1312 $set_attributes->( $self ) || return( $self->pass_error );
1313 }
1314 return( $self );
1315 }
1316 # Get mode
1317 else
1318 {
1319 # return( $self->children->map(sub{ $_->attributes->get( $classes[0] ) }) );
1320 # Get the value of an attribute for the first element in the set of matched elements.
1321 if( $self->isa_collection )
1322 {
1323 return( $self->children->first->attributes->get( $classes[0] ) );
1324 }
1325 else
1326 {
1327 return( $self->attributes->get( $classes[0] ) );
1328 }
1329 }
1330 }
1331  
1332 sub before { return( shift->_before_after( @_, { action => 'before' } ) ); }
1333  
1334 sub clearQueue { return( $_[0] ) }
1335  
1336 # Takes a selector; or
1337 # a selector and an HTML::Object::DOM::Element as a context; or
1338 # a HTML::Object::DOM::Element object
1339 # "Given a jQuery object that represents a set of DOM elements, the .closest() method searches through these elements and their ancestors in the DOM tree and constructs a new jQuery object from the matching elements."
1340 sub closest
1341 {
1342 my $self = shift( @_ );
1343 my $this = shift( @_ );
1344 my $context = shift( @_ );
1345 my $collection = $self->new_collection;
1346 return $collection if( !defined( $this ) );
1347 if( defined( $context ) &&
1348 ( !$self->_is_object( $context ) ||
1349 ( $self->_is_object( $context ) &&
1350 !$context->isa( 'HTML::Object::DOM::Element' )
1351 )
1352 ) )
1353 {
1354 return( $self->error( "Context provided (", overload::StrVal( $context ), ") is not an HTML::Object::DOM::Element." ) );
1355 }
1356 elsif( ref( $this ) &&
1357 $self->_is_object( $this ) &&
1358 ( !$this->isa( 'HTML::Object::DOM::Element' ) ||
1359 ( overload::Overloaded( $this ) && !overload::Method( $this, '""' ) )
1360 ) )
1361 {
1362 return( $self->error( "I was expecting a selector or an HTML::Object::DOM::Element, but instead received '$this'" ) );
1363 }
1364 else
1365 {
1366 return( $self->error( "I was expecting a selector or an HTML::Object::DOM::Element, but instead received '$this'" ) );
1367 }
1368  
1369 my $xpath;
1370 if( !ref( $this ) )
1371 {
1372 $xpath = $self->_xpath_value( $this );
1373 }
1374 my $process;
1375 $process = sub
1376 {
1377 my $elem = shift( @_ );
1378 # We reach the limit of our upward search
1379 return if( defined( $context ) && $elem->eid CORE::eq $context->eid );
1380 my $parent = $elem->parent;
1381 if( defined( $xpath ) )
1382 {
1383 if( $elem->matches( $xpath ) )
1384 {
1385 $collection->push( $elem );
1386 }
1387 }
1388 else
1389 {
1390 if( $elem->eid CORE::eq $this->eid )
1391 {
1392 $collection->push( $elem );
1393 }
1394 }
1395 return if( !$parent );
1396 return( $process->( $parent ) );
1397 };
1398 $process->( $self );
1399 return( $collection );
1400 }
1401  
1402 sub contains
1403 {
1404 my $self = shift( @_ );
1405 my( $container, $contained );
1406 if( scalar( @_ ) > 1 )
1407 {
1408 return( $self->error( "Wrong number of argument: \$el->contains( \$container, \$contained )" ) ) if( scalar( @_ ) > 2 );
1409 ( $container, $contained ) = @_;
1410 }
1411 elsif( scalar( @_ ) )
1412 {
1413 $container = $self;
1414 $contained = shift( @_ );
1415 }
1416 elsif( !ref( $self ) && scalar( @_ ) < 2 )
1417 {
1418 return( $self->error( "You need to provide 2 arguments when using contains() as a class function: xQuery->contains( \$container, \$contained )" ) );
1419 }
1420 else
1421 {
1422 return( $self->error( "No contained object provided to check." ) );
1423 }
1424 # We need an object to access certain methods
1425 my $this = ref( $self ) ? $self : HTML::Object::DOM->new;
1426 return( $self->error( "Container value provided is undefined." ) ) if( !defined( $container ) );
1427 return( $self->error( "Contained value provided is undefined." ) ) if( !defined( $contained ) );
1428 return( $this->false ) if( $this->_is_a( $contained => [qw( HTML::Object::DOM::Text HTML::Object::DOM::Comment )] ) );
1429 return( $self->error( "Container object provided is not an HTML::Object::DOM::Element" ) ) if( !$this->_is_a( $container => 'HTML::Object::DOM::Element' ) );
1430 return( $self->error( "Contained object provided is not an HTML::Object::DOM::Element" ) ) if( !$this->_is_a( $contained => 'HTML::Object::DOM::Element' ) );
1431 my $crawl;
1432 my $seen = {};
1433 $crawl = sub
1434 {
1435 my $kids = shift( @_ );
1436 my $grand_kids = $this->new_array;
1437 for( my $i = 0; $i < scalar( @$kids ); $i++ )
1438 {
1439 my $e = $kids->[$i];
1440 # Avoid recursion
1441 next if( ++$seen->{ $e->eid } > 1 );
1442 next unless( $this->_is_a( $e => 'HTML::Object::DOM::Element' ) );
1443 return( $this->true ) if( $e == $contained );
1444 $grand_kids->push( $e->children->list ) if( !$e->children->is_empty );
1445 }
1446 return( $this->false ) if( $grand_kids->is_empty );
1447 return( $crawl->( $grand_kids ) );
1448 };
1449 return( $crawl->( $container->children ) );
1450 }
1451  
1452 sub contents
1453 {
1454 my $self = shift( @_ );
1455 my $collection = $self->new_collection;
1456 my $children = $collection->children;
1457 if( $self->isa_collection )
1458 {
1459 $self->children->foreach(sub
1460 {
1461 $children->push( $_->children->list );
1462 });
1463 }
1464 else
1465 {
1466 $children->push( $self->children->list );
1467 }
1468 return( $collection );
1469 }
1470  
1471 # Takes a property name; or
1472 # an array reference of one or more css properties; or
1473 # a property name and a value; or
1474 # a property name and a function; or
1475 # an hash reference of property name-value pairs
1476 # <https://api.jquery.com/css/>
1477 # $e->css( $property_name );
1478 # $e->css( [$property_name1, $property_name2, $property_name3] );
1479 # $e->css( $property_name, $value );
1480 # $e->css( $property_name, $code_reference );
1481 # $e->css({ $property_name1 => $value1, $property_name2 => $value2 });
1482 # <https://api.jquery.com/css/>
1483 sub css
1484 {
1485 my $self = shift( @_ );
1486 # "An element should be connected to the DOM when calling .css()"
1487 return( $self->error( "Method css() must be called on an HTML::Object::DOM::Element." ) ) if( ( !$self->isa_element && !$self->isa_collection ) || $self->tag->substr( 0, 1 ) CORE::eq '_' );
1488 my( $name, $more ) = @_;
1489 return( $self->error( "No css property was provided." ) ) if( !defined( $name ) || !CORE::length( $name ) );
1490  
1491 my $process;
1492 $process = sub
1493 {
1494 my $elem = shift( @_ );
1495 my $style = $elem->attributes->get( 'style' );
1496 # return if( !defined( $style ) );
1497 my $css = CSS::Object->new( format => 'CSS::Object::Format::Inline', debug => $self->debug );
1498 my $cached;
1499 $cached = $elem->css_cache_check( $style ) if( defined( $style ) );
1500 if( $cached )
1501 {
1502 $css = $cached;
1503 }
1504 elsif( defined( $style ) )
1505 {
1506 # 'inline' here is just a fake selector to serve as a container rule for the inline properties,
1507 # because CSS::Object requires properties to be within a rule
1508 $css->read_string( 'inline {' . $style . ' }' ) ||
1509 return( $self->error( "Unable to parse existing style for tag name \"", $elem->prop( 'tagName' ), "\":", $css->error ) );
1510 }
1511 else
1512 {
1513 }
1514 my $main = $css->rules->first;
1515 # my $rule = defined( $main ) ? $css->builder->select( $main ) : $css->builder->select( 'inline' );
1516 my $rule;
1517  
1518 # Get the requested property values
1519 # $e->css( $property_name );
1520 # $e->css( [$property_name1, $property_name2, $property_name3] );
1521 # $e->css({ $property_name1 => $value1, $property_name2 => $value2 });
1522 if( $self->_is_array( $name ) ||
1523 $self->_is_hash( $name ) ||
1524 ( ( !ref( $name ) || overload::Method( $name, '""' ) ) && !defined( $more ) ) )
1525 {
1526 # If this is just 1 css property, we encapsulate it into an array to standardise our processing
1527 # $e->css( $property_name );
1528 $name = [ "$name" ] if( !defined( $more ) && ( !ref( $name ) || overload::Method( $name, '""' ) ) );
1529 # $e->css( [$property_name1, $property_name2, $property_name3] );
1530 # "assing an array of style properties to .css() will result in an object of property-value pairs."
1531 # <https://api.jquery.com/css/#css-propertyName>
1532 if( $self->_is_array( $name ) )
1533 {
1534 my $res = $self->new_hash;
1535 $self->new_array( $name )->foreach(sub
1536 {
1537 my $prop = shift( @_ );
1538 $prop =~ tr/_/-/;
1539 my $obj = $main->get_property_by_name( $prop );
1540 # next
1541 return(1) if( !defined( $obj ) );
1542 $res->{ $prop } = $obj->value->as_string;
1543 return(1);
1544 });
1545 return( $res );
1546 }
1547 # $e->css({ $property_name1 => $value1, $property_name2 => $value2 });
1548 elsif( $self->_is_hash( $name ) )
1549 {
1550 $rule = defined( $main ) ? $css->builder->select( $main ) : $css->builder->select( 'inline' );
1551 $self->new_hash( $name )->each(sub
1552 {
1553 my( $prop, $value ) = @_;
1554 my $obj = $main->get_property_by_name( $prop );
1555 # if the value is undef, remove the property from the set of css properties
1556 # "Setting the value of a style property to an empty string - e.g. $( "#mydiv" ).css( "color", "" ) - removes that property from an element if it has already been directly applied,"
1557 # <https://api.jquery.com/css/#css-propertyName-value>
1558 if( !defined( $value ) || !CORE::length( $value ) )
1559 {
1560 $main->element->remove( $obj ) if( $obj );
1561 }
1562 elsif( defined( $obj ) )
1563 {
1564 $obj->value( "$value" );
1565 }
1566 else
1567 {
1568 $main->$prop( "$value" );
1569 }
1570 });
1571 if( $rule->elements->length > 0 )
1572 {
1573 my $style = $rule->as_string;
1574 $elem->css_cache_store( $style, $css ) || return( $self->pass_error( $elem->error ) );
1575 $elem->attributes->set( style => $style );
1576 }
1577 else
1578 {
1579 }
1580 return( $self );
1581 }
1582 else
1583 {
1584 return( $self->error( "I was expecting a css property, or an array reference of css property, but instead I received '$name'." ) );
1585 }
1586 }
1587 else
1588 {
1589 # Set css property values
1590 # $e->css( $property_name, $value );
1591 # $e->css( $property_name, $code_reference );
1592 if( defined( $more ) )
1593 {
1594 return( $self->error( "More than 2 arguments were provided. I was expecting a property and its value or a function." ) ) if( scalar( @_ ) > 2 );
1595 $rule = defined( $main ) ? $css->builder->select( $main ) : $css->builder->select( 'inline' );
1596 # $e->css( $property_name, $code_reference );
1597 if( ref( $more ) CORE::eq 'CODE' )
1598 {
1599 my $pos = $elem->parent ? $elem->parent->children->pos( $elem ) : 0;
1600 $name =~ tr/_/-/;
1601 my $obj = $main->get_property_by_name( $name );
1602 my $val;
1603 if( defined( $obj ) )
1604 {
1605 $val = $obj->value->as_string;
1606 }
1607 local $_ = $elem;
1608 my $ret = $more->( $pos, $val );
1609 # "If nothing is returned in the setter function (ie. function( index, style ){} ), or if undefined is returned, the current value is not changed. This is useful for selectively setting values only when certain criteria are met."
1610 # <https://api.jquery.com/css/#css-propertyName-function>
1611 return( $elem ) if( !defined( $ret ) || !CORE::length( $ret ) );
1612 if( defined( $obj ) )
1613 {
1614 $obj->value( "$val" );
1615 }
1616 else
1617 {
1618 $rule->$name( "$val" );
1619 }
1620 }
1621 # $e->css( $property_name, $value );
1622 else
1623 {
1624 return( $self->error( "I was expecting a value as a string, but instead got '$more'." ) ) if( ref( $more ) && !( overload::Overloaded( $more ) && overload::Method( $more, '""' ) ) );
1625 $name =~ tr/_/-/;
1626 my $obj = $rule->get_property_by_name( $name );
1627 if( defined( $obj ) )
1628 {
1629 $obj->value( "$more" );
1630 }
1631 else
1632 {
1633 $rule->$name( "$more" );
1634 }
1635 }
1636 }
1637  
1638 if( defined( $rule ) && $rule->elements->length > 0 )
1639 {
1640 my $style = $rule->as_string;
1641 $elem->css_cache_store( $style, $css ) || return( $self->pass_error( $elem->error ) );
1642 $elem->attributes->set( style => $style );
1643 }
1644 else
1645 {
1646 }
1647 return( $elem );
1648 }
1649 };
1650  
1651 if( $self->isa_collection )
1652 {
1653 $self->children->foreach(sub
1654 {
1655 $_->reset(1);
1656 $process->( $_ );
1657 });
1658 return( $self );
1659 }
1660 else
1661 {
1662 $self->reset(1);
1663 return( $process->( $self ) );
1664 }
1665 }
1666  
1667 sub css_cache_check
1668 {
1669 my $self = shift( @_ );
1670 # my $data = shift( @_ );
1671 # return if( !defined( $data ) );
1672 return( $self->error( "css_cache_check() must be called on an HTML element, not a collection." ) ) if( $self->isa_collection );
1673 my $internal = $self->internal;
1674 $internal->{css_cache} //= {};
1675 if( exists( $internal->{css_cache} ) )
1676 {
1677 my $css = $internal->{css_cache}->{object} ||
1678 return( $self->error( "CSS object could not be found in cache!" ) );
1679 # return( $css->clone );
1680 # my $clone = $css->clone;
1681 # return( $clone );
1682 return( $css );
1683 }
1684 return( '' );
1685 }
1686  
1687 sub css_cache_store
1688 {
1689 my $self = shift( @_ );
1690 my $data = shift( @_ );
1691 return if( !defined( $data ) );
1692 return( $self->error( "css_cache_store() must be called on an HTML element, not a collection." ) ) if( $self->isa_collection );
1693 my $css = shift( @_ );
1694 return( $self->error( "No css object provided to store in the element cache." ) ) if( !$self->_is_object( $css ) );
1695 my $trace = $self->_get_stack_trace;
1696 my $internal = $self->internal;
1697 $internal->{css_cache} =
1698 {
1699 timestamp => time(),
1700 # object => $css->clone,
1701 object => $css,
1702 };
1703 return( $self );
1704 }
1705  
1706 # sub data { return( shift->attr( join( '-', 'data', shift( @_ ) ) => shift( @_ ) ) ) }
1707 # nothing which returns everything as a hash; or
1708 # a key-value pair; or
1709 # a hash reference
1710 sub data
1711 {
1712 my $self = shift( @_ );
1713 my( $this, $val ) = @_;
1714 my $elem;
1715 if( $self->isa_collection )
1716 {
1717 $elem = $self->children->first;
1718 }
1719 # elsif( $self->tag->substr( 0, 1 ) eq '_' )
1720 elsif( !$self->_is_a( $self => 'HTML::Object::DOM::Element' ) )
1721 {
1722 return( $self->error( "You can only call the data method on HTML elements." ) );
1723 }
1724 else
1725 {
1726 $elem = $self;
1727 }
1728  
1729 if( $self->_is_hash( $this ) )
1730 {
1731 my $changed = 0;
1732 $this = $self->new_hash( $this )->each(sub
1733 {
1734 my( $k, $v ) = @_;
1735 # Remove leading and trailing spaces if this is not a reference
1736 $v =~ s/^[[:blank:]\h]+|[[:blank:]\h]+$//g if( !ref( $v ) );
1737 # $attr->set( 'data-' . $k, $v );
1738 if( $elem->setAttribute( 'data-' . $k, $v ) )
1739 {
1740 $changed++;
1741 }
1742 });
1743 $elem->reset(1) if( $changed );
1744 return( $elem );
1745 }
1746 elsif( defined( $this ) && scalar( @_ ) > 1 )
1747 {
1748 # From jQuery documentation: "undefined is not recognized as a data value. Calls such as .data( "name", undefined ) will return the jQuery object that it was called on, allowing for chaining."
1749 return( $self ) if( !defined( $val ) );
1750 return( $self->error( "I was provided data name '$this', but I was expcting a regular string." ) ) if( ref( $this ) && ( !overload::Overloaded( $this ) || ( overload::Overloaded( $this ) && !overload::Method( $this, '""' ) ) ) );
1751 # $attr->set( 'data-' . $this => $val );
1752 if( $elem->setAttribute( 'data-' . $this => $val ) )
1753 {
1754 $elem->reset(1);
1755 }
1756 return( $elem );
1757 }
1758 elsif( defined( $this ) && scalar( @_ ) == 1 )
1759 {
1760 # return( $attr->get( $this ) );
1761 return( $elem->getAttribute( 'data-' . $this ) );
1762 }
1763 else
1764 {
1765 $self->_load_class( 'Module::Generic::Dynamic' ) || return( $self->pass_error );
1766 my $ref = {};
1767 my $attr = $elem->attributes;
1768 $attr->each(sub
1769 {
1770 my( $k, $v ) = @_;
1771 if( substr( $k, 0, 5 ) CORE::eq 'data-' && CORE::length( $k ) > 5 )
1772 {
1773 $ref->{ substr( $k, 5 ) } = $v;
1774 }
1775 });
1776 my $obj = Module::Generic::Dynamic->new( $ref ) ||
1777 return( $self->pass_error( Module::Generic::Dynamic->error ) );
1778 return( $obj );
1779 }
1780 }
1781  
1782 sub debug
1783 {
1784 my $self = shift( @_ );
1785 if( @_ )
1786 {
1787 my $val = $self->SUPER::debug( @_ );
1788 if( $self->isa_collection )
1789 {
1790 $self->children->foreach(sub
1791 {
1792 $_->debug( $val );
1793 });
1794 }
1795 return( $val );
1796 }
1797 return( $self->SUPER::debug );
1798 }
1799  
1800 sub dequeue { return( $_[0] ) }
1801  
1802 # TODO: Instead of adding this method, maybe we should change the one in HTML::Object::DOM::Element to have it return $self instead of $parent, because otherwise there is no difference
1803 sub detach
1804 {
1805 my $self = shift( @_ );
1806 # If this is a collection, walk through its children
1807 if( $self->isa_collection )
1808 {
1809 $self->children->foreach(sub
1810 {
1811 my $e = shift( @_ );
1812 my $parent = $e->parent;
1813 return(1) if( !$parent );
1814 my $pos = $parent->children->pos( $e );
1815 $parent->children->splice( $pos, 1 );
1816 $e->parent( undef() );
1817 $parent->reset(1);
1818 });
1819 }
1820 # otherwise, process this one element individually
1821 else
1822 {
1823 my $parent = $self->parent;
1824 return( $self ) if( !$parent );
1825 my $pos = $parent->children->pos( $self );
1826 if( defined( $pos ) )
1827 {
1828 $parent->children->splice( $pos, 1 );
1829 $self->parent( undef() );
1830 $parent->reset(1);
1831 }
1832 }
1833 return( $self );
1834 }
1835  
1836 # Takes a code reference which receives the element position and element object as parameter
1837 # It returns the current object it was called with
1838 sub each
1839 {
1840 my( $self, $code ) = @_;
1841 return( $self->error( "I was expecting a code reference to pass it the element position and element object, but instead I got \"", overload::StrVal( $code ), "\"." ) ) if( ref( $code ) ne 'CODE' );
1842 # Make a copy of the array so that call to code ref that may remove a child element does not alter our looping operation through all the children
1843 $self->children->clone->for(sub
1844 {
1845 my( $i, $e ) = @_;
1846 $code->( $i, $e );
1847 });
1848 return( $self );
1849 }
1850  
1851 sub empty
1852 {
1853 my $self = shift( @_ );
1854 # Element object of Collection object, it does not matter
1855 $self->children->reset;
1856 $self->reset(1);
1857 return( $self );
1858 }
1859  
1860 sub end { return( shift->_set_get_object({
1861 field => 'end',
1862 weaken => 1,
1863 }, 'HTML::Object::DOM::Element', @_ ) ); }
1864  
1865 sub eq { return( shift->children->index( shift( @_ ) ) ); }
1866  
1867 # Returns a new collection of elements whose position is an even number
1868 sub even
1869 {
1870 my $self = shift( @_ );
1871 return( $self ) unless( $self->isa_collection );
1872 my $even = $self->children->even;
1873 my $collection = $self->new_collection;
1874 $collection->children( $even );
1875 return( $collection );
1876 }
1877  
1878 sub exists
1879 {
1880 my( $self, $path ) = @_;
1881 return( $self->xp->exists( $path, $self ) );
1882 }
1883  
1884 # Takes a selector; or
1885 # function with arguments are element position (starting from 0) and the element itself, expecting a true value in return; or
1886 # an array of element objects; or
1887 # an element object;
1888 sub filter
1889 {
1890 my $self = shift( @_ );
1891 my $this = shift( @_ );
1892 my $collection = $self->new_collection( end => $self );
1893 return( $collection ) if( !defined( $this ) );
1894 if( !ref( $this ) ||
1895 ( ref( $this ) &&
1896 overload::Overloaded( $this ) &&
1897 overload::Method( $this, '""' )
1898 ) )
1899 {
1900 my $xpath = $self->_xpath_value( "$this" ) || return;
1901 if( $self->isa_collection )
1902 {
1903 $self->children->foreach(sub
1904 {
1905 # $_->debug( $self->debug );
1906 if( $_->tag->substr( 0, 1 ) ne '_' &&
1907 $_->matches( $xpath ) )
1908 {
1909 $collection->children->push( $_ );
1910 }
1911 else
1912 {
1913 # No match
1914 }
1915 });
1916 }
1917 elsif( $self->tag->substr( 0, 1 ) ne '_' && $self->matches( $xpath ) )
1918 {
1919 $collection->children->push( $self );
1920 }
1921 }
1922 elsif( ref( $this ) eq 'CODE' )
1923 {
1924 if( $self->isa_collection )
1925 {
1926 $self->children->for(sub
1927 {
1928 my( $i, $e ) = @_;
1929 local $_ = $e;
1930 if( $this->( $i, $e ) )
1931 {
1932 $collection->children->push( $e );
1933 }
1934 });
1935 }
1936 elsif( $self->isa( 'HTML::Object::DOM::Element' ) )
1937 {
1938 return( $collection ) if( $self->tag->substr( 0, 1 ) eq '_' );
1939 local $_ = $self;
1940 $collection->children->push( $self ) if( $this->( 0, $self ) );
1941 }
1942 }
1943 elsif( $self->_is_array( $this ) || $self->_is_object( $this ) )
1944 {
1945 if( $self->_is_object( $this ) &&
1946 ( !$this->isa( 'HTML::Object::DOM::Element' ) ||
1947 (
1948 # Probably need to change this to HTML::Object::DOM::Node
1949 $this->isa( 'HTML::Object::Element' ) &&
1950 $this->tag->substr( 0, 1 ) eq '_' &&
1951 !$this->isa( 'HTML::Object::Collection' )
1952 )
1953 ) )
1954 {
1955 return( $self->error( "Object of class \"", ref( $this ), "\", but you can only provide an HTML::Object::DOM::Element or an HTML::Object::Collection object." ) );
1956 }
1957 my $a = $self->new_array( $self->_is_array( $this ) ? $this : [ $this ] );
1958 $a->foreach(sub
1959 {
1960 my $xpath = $_->getNodePath();
1961 if( $self->isa_collection )
1962 {
1963 $self->children->foreach(sub
1964 {
1965 my $e = shift( @_ );
1966 if( $e->matches( $xpath ) )
1967 {
1968 $collection->children->push( $e );
1969 }
1970 });
1971 }
1972 elsif( $self->matches( $xpath ) )
1973 {
1974 $collection->children->push( $self );
1975 }
1976 });
1977 }
1978 else
1979 {
1980 return( $self->error( "I was expecting a selector, a code reference, an array of elements or an element to use in filter(), but instead I got '$this', and I do not know what to do with it." ) );
1981 }
1982 return( $collection );
1983 }
1984  
1985 # Takes a selector; or
1986 # Element object
1987 sub find
1988 {
1989 my( $self, $this ) = @_;
1990 my $collection = $self->new_collection;
1991 return( $collection ) if( !defined( $this ) );
1992  
1993 if( ref( $this ) && $self->_is_object( $this ) && $this->isa( 'HTML::Object::DOM::Element' ) )
1994 {
1995 my $a = $self->new_array( $self->isa_collection( $this ) ? $this->children : [ $this ] );
1996 my $lookup;
1997 $lookup = sub
1998 {
1999 my $kids = shift( @_ );
2000 $kids->foreach(sub
2001 {
2002 my $child = shift( @_ );
2003 $a->foreach(sub
2004 {
2005 my $candidate = shift( @_ );
2006 if( $child->eid eq $candidate->eid )
2007 {
2008 $collection->children->push( $child );
2009 # We've added this child. Move to next child.
2010 return(1);
2011 }
2012 });
2013 if( $child->children->length > 0 )
2014 {
2015 $lookup->( $child->children );
2016 }
2017 });
2018 };
2019 # Wether this is a collection or just an element object, we check our children
2020 $lookup->( $self->children );
2021 }
2022 # I am expecting an xpath value
2023 else
2024 {
2025 if( ref( $this ) &&
2026 (
2027 !overload::Overloaded( $this ) ||
2028 ( overload::Overloaded( $this ) && !overload::Method( $this, '\"\"' ) )
2029 ) )
2030 {
2031 return( $self->error( "I was expecting an xpath string, but instead I got '$this'." ) );
2032 }
2033  
2034 # Fast paths pour les sélecteurs simples - évite le pipeline XPath complet
2035 my $str = "$this";
2036  
2037 # Fast path: #id
2038 if( $str =~ /\A#([\w][\w-]*)\z/ )
2039 {
2040 my $id = $1;
2041 my $found = $self->_fast_find_by(sub
2042 {
2043 my $e = shift( @_ );
2044 my $v = $e->attributes->get( 'id' );
2045 return( defined( $v ) && $v eq $id );
2046 });
2047 $collection->children->push( $found->list );
2048 return( $collection );
2049 }
2050 # Fast path: .class (une seule classe, pas de combinaison)
2051 elsif( $str =~ /\A\.([\w][\w-]*)\z/ )
2052 {
2053 my $class = $1;
2054 my $found = $self->_fast_find_by(sub
2055 {
2056 my $e = shift( @_ );
2057 my $v = $e->attributes->get( 'class' );
2058 return( defined( $v ) && $v =~ /(?:\A|[[:blank:]\h]+)\Q${class}\E(?:[[:blank:]\h]+|\Z)/ );
2059 });
2060 $collection->children->push( $found->list );
2061 return( $collection );
2062 }
2063 # Fast path: tag simple (lettres uniquement, pas de combinaison)
2064 elsif( $str =~ /\A([a-zA-Z][a-zA-Z0-9]*)\z/ )
2065 {
2066 my $tag = lc( $1 );
2067 my $found = $self->_fast_find_by(sub
2068 {
2069 my $e = shift( @_ );
2070 return( lc( "$e->{tag}" ) eq $tag );
2071 });
2072 $collection->children->push( $found->list );
2073 return( $collection );
2074 }
2075  
2076 # Fallback : pipeline XPath complet
2077 my $xpath = $self->_xpath_value( $str ) || return( $self->pass_error );
2078 # $self->children->foreach(sub
2079 # {
2080 # my $child = shift( @_ );
2081 # # Propagate debug value
2082 # $child->debug( $self->debug );
2083 # try
2084 # {
2085 # my @nodes = $child->findnodes( $xpath );
2086 # $collection->children->push( @nodes );
2087 # }
2088 # catch( $e )
2089 # {
2090 # warn( "Error while calling findnodes on element id \"", $_->id, "\" and tag \"", $_->tag, "\": $e\n" );
2091 # }
2092 # });
2093 # try-catch
2094 local $@;
2095 eval
2096 {
2097 my @nodes = $self->findnodes( $xpath );
2098 $collection->children->push( @nodes );
2099 };
2100 if( $@ )
2101 {
2102 warn( "Error while calling findnodes on element id \"", $self->id, "\" and tag \"", $self->tag, "\": $@\n" );
2103 }
2104 }
2105 return( $collection );
2106 }
2107  
2108 sub find_xpath
2109 {
2110 my( $self, $path ) = @_;
2111 return( $self->xp->find( $path, $self ) );
2112 }
2113  
2114 sub findnodes
2115 {
2116 my( $self, $path ) = @_;
2117 # xp()->debug( $self->debug );
2118 return( $self->xp->findnodes( $path, $self ) );
2119 }
2120  
2121 sub findnodes_as_string
2122 {
2123 my( $self, $path ) = @_;
2124 return( $self->xp->findnodes_as_string( $path, $self ) );
2125 }
2126  
2127 sub findnodes_as_strings
2128 {
2129 my( $self, $path ) = @_;
2130 return( $self->xp->findnodes_as_strings( $path, $self ) );
2131 }
2132  
2133 sub findvalue
2134 {
2135 my( $self, $path ) = @_;
2136 return( $self->xp->findvalue( $path, $self ) );
2137 }
2138  
2139 sub findvalues
2140 {
2141 my( $self, $path ) = @_;
2142 return( $self->xp->findvalues( $path, $self ) );
2143 }
2144  
2145 sub first
2146 {
2147 my $self = shift( @_ );
2148 my $collection = $self->new_collection;
2149 if( $self->isa_collection )
2150 {
2151 return( $self->children->first );
2152 }
2153 else
2154 {
2155 return( $self );
2156 }
2157 }
2158  
2159 # <https://api.jquery.com/get/>
2160 sub get
2161 {
2162 my $self = shift( @_ );
2163 my $idx = shift( @_ );
2164 if( $self->isa_collection )
2165 {
2166 if( defined( $idx ) )
2167 {
2168 return( $self->error( "Index value provided is not an integer." ) ) if( !$self->_is_integer( $idx ) );
2169 return( $self->children->[ $idx ] );
2170 }
2171 else
2172 {
2173 my $arr = $self->new_array;
2174 $arr->push( $self->children->list );
2175 return( $arr );
2176 }
2177 }
2178 else
2179 {
2180 if( defined( $idx ) )
2181 {
2182 return( $self );
2183 }
2184 else
2185 {
2186 return( $self->new_array( $self ) );
2187 }
2188 }
2189 }
2190  
2191 sub getDataJson
2192 {
2193 my $self = shift( @_ );
2194 my $dataName = shift( @_ ) ||
2195 return( $self->error( "No data name was provided to get its JSON object" ) );
2196 my $el;
2197 if( $self->isa_collection )
2198 {
2199 $el = $self->children->first;
2200 return({}) if( !$el );
2201 }
2202 else
2203 {
2204 $el = $self;
2205 }
2206 my $json;
2207 my $shortName = $dataName;
2208 if( substr( $dataName, 0, 5 ) eq 'data-' )
2209 {
2210 $shortName = substr( $dataName, 5, length( $dataName ) );
2211 }
2212 my $data = $self->data( $shortName );
2213 return({}) if( !defined( $data ) || !length( $data // '' ) );
2214 if( ref( $data ) eq 'HASH' )
2215 {
2216 $json = $data;
2217 }
2218 else
2219 {
2220 # Taken from URI::Escape
2221 my $decodeURIComponent = sub
2222 {
2223 my $str = shift( @_ );
2224 if( @_ && wantarray )
2225 {
2226 # not executed for the common case of a single argument
2227 # need to copy
2228 my @str = ( $str, @_ );
2229 for( @str )
2230 {
2231 s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
2232 }
2233 return( @str );
2234 }
2235 $str =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg if( defined( $str ) );
2236 return( $str );
2237 };
2238 # try-catch
2239 local $@;
2240 eval
2241 {
2242 my $j = $self->new_json;
2243 if( index( $data, '{' ) != -1 )
2244 {
2245 $json = $j->decode( $data );
2246 }
2247 else
2248 {
2249 $json = $j->decode( $decodeURIComponent->( $data ) );
2250 }
2251 };
2252 if( $@ )
2253 {
2254 return( $self->error( "An error occurred while trying to decode the json data: $@" ) );
2255 }
2256 # Replace parsed json string by its object representation
2257 $self->data( $shortName => $json );
2258 }
2259 return( $json );
2260 }
2261  
2262 sub getJSON
2263 {
2264 my $self = shift( @_ );
2265 my $url = shift( @_ ) || return( $self->error( "No URL was provided." ) );
2266 my @args = @_;
2267 my( $data, $success );
2268 for( my $i = 0; $i < scalar( @args ); $i++ )
2269 {
2270 if( !defined( $data ) && ref( $args[$i] // '' ) eq 'HASH' )
2271 {
2272 $data = $args[$i];
2273 }
2274 elsif( !defined( $success ) && ref( $args[$i] // '' ) eq 'CODE' )
2275 {
2276 $success = $args[$i];
2277 }
2278 }
2279  
2280 $self->_load_class( 'Promise::Me' ) || return( $self->pass_error );
2281 if( lc( substr( "$url", 0, 7 ) ) eq 'file://' )
2282 {
2283 $self->_load_class( 'HTTP::Promise::Response' ) || return( $self->pass_error );
2284 return( Promise::Me->new(sub
2285 {
2286 my( $resolve, $reject ) = @$_;
2287 my $f = $self->new_file( $url ) || return( $reject->( $self->error ) );
2288 if( $f->exists )
2289 {
2290 my $ref = $f->load_json || return( $reject->( $f->error ) );
2291 my $resp2 = HTTP::Promise::Response->new( 200 => 'OK' );
2292 if( defined( $success ) )
2293 {
2294 my $ua = HTTP::Promise->new;
2295 $success->( $ref, 'success', $resp2, $ua );
2296 }
2297 return( $resolve->( $ref, 'success', $resp2 ) );
2298 }
2299 else
2300 {
2301 my $resp2 = HTTP::Promise::Response->new( 404 => 'Not found' );
2302 my $err = "File $url is not found.";
2303 if( defined( $success ) )
2304 {
2305 my $ua = HTTP::Promise->new;
2306 $success->( $err, 'error', $resp2, $ua );
2307 }
2308 $self->error({
2309 code => 404,
2310 message => $err,
2311 });
2312 my $ex = $self->error;
2313 return( $reject->( $ex ) );
2314 }
2315 }) );
2316 }
2317 else
2318 {
2319 return( Promise::Me->new(sub
2320 {
2321 my( $resolve, $reject ) = @$_;
2322 my( $uri, $doc_root, $doc_uri );
2323 if( lc( substr( $url, 0, 7 ) ) eq 'http://' ||
2324 lc( substr( $url, 0, 7 ) ) eq 'http://' )
2325 {
2326 $uri = $url;
2327 }
2328 # Contextual URL that requires a base URL.
2329 # We check for documentURI of the root element, if any
2330 elsif( ( substr( $url, 0, 1 ) eq '/' ||
2331 substr( $url, 0, 2 ) eq './' ||
2332 substr( $url, 0, 3 ) eq '../' ) &&
2333 ( $doc_root = $self->getRootNode ) &&
2334 $doc_root->isa( 'HTML::Object::DOM::Document' ) &&
2335 ( $doc_uri = $doc_root->documentURI ) )
2336 {
2337 $uri = $doc_uri->clone;
2338 $uri->path( $url );
2339 }
2340 else
2341 {
2342 $self->error( "Unsupported URL '${url}'" );
2343 return( $reject->( $self->error ) );
2344 }
2345 $self->ajax( $uri,
2346 dataType => 'json',
2347 ( defined( $data ) ? ( data => $data ) : () ),
2348 ( defined( $success ) ? ( success => $success ) : () ),
2349 )->catch(sub
2350 {
2351 return( $reject->( @_ ) );
2352 });
2353 }) );
2354 }
2355 }
2356  
2357 sub has
2358 {
2359 my $self = shift( @_ );
2360 my $this = shift( @_ );
2361 my $collection = $self->new_collection;
2362 return( $collection ) if( !defined( $this ) );
2363 if( ref( $this ) && $self->_is_object( $this ) && $self->isa( 'HTML::Object::DOM::Element' ) )
2364 {
2365 my $lookup;
2366 $lookup = sub
2367 {
2368 my $kids = shift( @_ );
2369 my $found;
2370 $kids->foreach(sub
2371 {
2372 my $child = shift( @_ );
2373 $this->children->foreach(sub
2374 {
2375 my $candidate = shift( @_ );
2376 # Found a match, no need to look down further
2377 if( $child->eid eq $candidate->eid )
2378 {
2379 $found = $child;
2380 return( $kids->return( undef() ) );
2381 }
2382 });
2383 if( $child->children->length )
2384 {
2385 my $rc = $lookup->( $child->children );
2386 if( $rc )
2387 {
2388 $found = $rc;
2389 return( $kids->return( undef() ) );
2390 }
2391 }
2392 });
2393 return( $found );
2394 };
2395 $self->children->foreach(sub
2396 {
2397 $collection->children->push( $_ ) if( $lookup->( $_->children ) );
2398 });
2399 }
2400 # An xpath then?
2401 else
2402 {
2403 if( ref( $this ) &&
2404 (
2405 !overload::Overloaded( $this ) ||
2406 ( overload::Overloaded( $this ) && !overload::Method( $this, '""' ) )
2407 ) )
2408 {
2409 return( $self->error( "I was expecting an xpath value, but got '$this' instead." ) );
2410 }
2411 my $xpath = $self->_xpath_value( "$this" ) || return;
2412  
2413 my $lookup;
2414 $lookup = sub
2415 {
2416 my $kids = shift( @_ );
2417 my $found;
2418 $kids->foreach(sub
2419 {
2420 my $child = shift( @_ );
2421 if( $child->matches( $xpath ) )
2422 {
2423 $found = $child;
2424 # No need to look further, we found a match
2425 return(1);
2426 }
2427 if( $child->children->length > 0 )
2428 {
2429 my $rc = $lookup->( $child->children );
2430 if( $rc )
2431 {
2432 $found = $rc;
2433 return(1);
2434 }
2435 }
2436 });
2437 return( $found );
2438 };
2439  
2440 $self->children->foreach(sub
2441 {
2442 $collection->children->push( $_ ) if( $lookup->( $_->children ) );
2443 });
2444 }
2445 return( $collection );
2446 }
2447  
2448 sub hasClass
2449 {
2450 my $self = shift( @_ );
2451 my $class = shift( @_ );
2452 return(0) if( !CORE::length( $class ) );
2453 my $found = 0;
2454 if( $self->isa_collection )
2455 {
2456 $self->children->foreach(sub
2457 {
2458 my $e = shift( @_ );
2459 my $classes = $e->attributes->get( 'class' );
2460 # No class attribute, skip to next element
2461 return(1) if( !defined( $classes ) );
2462 # Found a match, no need to go further since we only need to return true or false
2463 if( $classes =~ /(?:\A|[[:blank:]\h]+)${class}(?:[[:blank:]\h]+|\Z)/ )
2464 {
2465 $found++;
2466 return(0);
2467 }
2468 return(1);
2469 });
2470 }
2471 else
2472 {
2473 my $classes = $self->attributes->get( 'class' );
2474 return(0) if( !defined( $classes ) );
2475 return(1) if( $classes =~ /(?:\A|[[:blank:]\h]+)${class}(?:[[:blank:]\h]+|\Z)/ );
2476 return(0);
2477 }
2478 }
2479  
2480 # Since this is a perl context, this only set the inline css to "display: none" like jQuery actually does
2481 # Any parameter provided will be ignored
2482 # See the show() method for its alter ego
2483 sub hide
2484 {
2485 my $self = shift( @_ );
2486 my( $this, $code ) = @_;
2487 $code = $this if( ref( $this ) eq 'CODE' && !defined( $code ) );
2488 my $process;
2489 $process = sub
2490 {
2491 my $e = shift( @_ );
2492 my $internal = $e->internal;
2493 my $rule = $self->_css_object();
2494 if( defined( $rule ) )
2495 {
2496 my $display = $rule->get_property_by_name( 'display' );
2497 my $val = $display->value;
2498 # $val may be undefined if it was not set in the first place, and that's ok
2499 # when we'll restore it with show(), we'll see the original value was empty and
2500 # we'll just remove the "display: none"
2501 # Here we check what the current value is, because, if it is already set to none, we just ignore it
2502 if( $val ne 'none' )
2503 {
2504 $internal->{css_display_value} = $val;
2505 }
2506 $display->value( 'none' );
2507 }
2508 else
2509 {
2510 $rule = $self->_css_builder;
2511 $rule->display( 'none' );
2512 }
2513 if( $rule->elements->length > 0 )
2514 {
2515 $e->_css_object( $rule );
2516 }
2517 };
2518  
2519 if( $self->isa_collection )
2520 {
2521 $self->children->foreach(sub
2522 {
2523 $process->( $_ );
2524 });
2525 }
2526 elsif( $self->tag->substr( 0, 1 ) eq '_' )
2527 {
2528 return( $self->error( "You can only use the hide() or show() method on html object elements. The element you are calling hide() with is an object of class \"", ref( $self ), "\"." ) );
2529 }
2530 else
2531 {
2532 $process->( $self );
2533 }
2534 }
2535  
2536 # This takes either no arguments and it returns the inner html; or
2537 # it takes an html string to replace its content; or
2538 # it takes a code reference that is called with the index position in the set of element and
2539 # the current html data. It returns the new html data
2540 # See also text() method
2541 sub html
2542 {
2543 my $self = shift( @_ );
2544 my $this = shift( @_ );
2545 if( defined( $this ) )
2546 {
2547 if( !ref( $this ) ||
2548 ( ref( $this ) && overload::Overloaded( $this ) && overload::Method( $this, '""' ) ) )
2549 {
2550 my $p = $self->new_parser;
2551 my $res = $p->parse_data( "$this" ) ||
2552 return( $self->error( "Error while parsing html data provided: ", $p->error ) );
2553 $this = $res;
2554 }
2555 elsif( ref( $this ) ne 'CODE' )
2556 {
2557 return( $self->error( "I was expecting some html data or a code reference in replacement of html for this element \"", $self->tag, "\", but instead got '$this'." ) );
2558 }
2559  
2560 my $is_code = ref( $this ) eq 'CODE' ? 1 : 0;
2561 my $process = sub
2562 {
2563 my( $e, $i ) = @_;
2564 if( $is_code )
2565 {
2566 my $current_html = $e->as_string;
2567 my $html = $this->( $i, $current_html );
2568 if( !defined( $html ) || !CORE::length( $html ) )
2569 {
2570 $e->empty();
2571 # Next please
2572 return(1);
2573 }
2574 # We were provided with an HTML::Object::DOM::Element in response, we use its children as the new content
2575 elsif( ref( $html ) && $self->_is_object( $html ) && $html->isa( 'HTML::Object::DOM::Element' ) )
2576 {
2577 if( $html->tag->substr( 0, 1 ) eq '_' && !$html->isa_collection )
2578 {
2579 warn( "You cannot use this object of class ", ref( $html ), " to set its children as the new html. You can only use html element objects.\n" );
2580 return(1);
2581 }
2582 $e->children( $html->children );
2583 $html->children->foreach(sub
2584 {
2585 $_->parent( $e );
2586 });
2587 $e->reset(1);
2588 return(1);
2589 }
2590 elsif( ref( $html ) &&
2591 !( overload::Overloaded( $html ) && overload::Method( $html, '""' ) ) )
2592 {
2593 warn( "I was provided a reference '$html' as a result from calling this code reference to get the replacement html for tag \"", $e->tag, "\", but I do not know what to do with it.\n" );
2594 return(1);
2595 }
2596 my $p = $self->new_parser;
2597 my $doc = $p->parse_data( "$html" ) || do
2598 {
2599 warn( "Error while trying to parse html data returned by code reference supplied: ", $p->error, "\n" );
2600 # Switch to next element
2601 return(1);
2602 };
2603 # Replace the children element by the new ones found in parsing.
2604 $e->children( $doc->children );
2605 $doc->children->foreach(sub
2606 {
2607 $_->parent( $e );
2608 });
2609 $e->reset(1);
2610 }
2611 # It's an HTML::Object::DOM::Document object
2612 else
2613 {
2614 my $a = $self->new_array;
2615 $this->children->foreach(sub
2616 {
2617 $a->push( $_->clone );
2618 });
2619 $e->children( $a );
2620 $e->reset(1);
2621 }
2622 };
2623  
2624 if( $self->isa_collection )
2625 {
2626 $self->children->for(sub
2627 {
2628 my( $i, $e ) = @_;
2629 $process->( $e, $i );
2630 # Return true at the end to satisfy Module::Generic::Array->for
2631 return(1);
2632 });
2633 }
2634 else
2635 {
2636 $process->( $self, 0 );
2637 }
2638 }
2639 else
2640 {
2641 # "Get the HTML contents of the first element in the set of matched elements."
2642 my $elem = $self->isa_collection ? $self->children->first : $self;
2643 return( '' ) unless( $self );
2644 # Create a new document, because we want to use the document object as_string function which produce a string of its children, and no need to reproduce it here
2645 my $doc = $elem->new_document;
2646 $doc->children( $elem->children );
2647 return( $doc->as_string );
2648 }
2649 }
2650  
2651 sub id
2652 {
2653 my $self = shift( @_ );
2654 if( @_ )
2655 {
2656 if( $self->isa_collection )
2657 {
2658 return( $self->error( "Cannot set an id on a collection" ) );
2659 }
2660 else
2661 {
2662 # Method in HTML::Object::DOM::Element
2663 return( $self->_set_get_id( @_ ) );
2664 }
2665 }
2666 else
2667 {
2668 my $e = $self;
2669 if( $self->isa_collection )
2670 {
2671 my $first = $self->children->first;
2672 return if( !$first || !$self->isa_element( $first ) );
2673 $e = $first;
2674 }
2675 my $id = $e->attributes->get( 'id' );
2676 return( $e->new_scalar( $id ) );
2677 }
2678 }
2679  
2680 # Takes either nothing; or
2681 # a selector; or
2682 # an element object
2683 sub index
2684 {
2685 my $self = shift( @_ );
2686 my $this = shift( @_ );
2687 if( defined( $this ) )
2688 {
2689 if( !ref( $this ) ||
2690 ( ref( $this ) && overload::Overloaded( $this ) && overload::Method( $this, '""' ) ) )
2691 {
2692 my $xpath = $self->_xpath_value( "$this" );
2693 if( $self->isa_collection() )
2694 {
2695 my $found;
2696 $self->children->for(sub
2697 {
2698 my( $i, $e ) = @_;
2699 if( $e->matches( $xpath ) )
2700 {
2701 $found = $i;
2702 # Exit the for loop
2703 return(1);
2704 }
2705 });
2706 return( $self->new_number(-1) ) if( !defined( $found ) );
2707 return( $self->new_number( $found ) );
2708 }
2709 else
2710 {
2711 if( $self->matches( $xpath ) )
2712 {
2713 return( $self->new_number(0) ) if( !$self->parent );
2714 my $pos = $self->parent->children->pos( $self );
2715 return( $self->new_number( defined( $pos ) ? $pos : -1 ) );
2716 }
2717 else
2718 {
2719 return( $self->new_number(-1) );
2720 }
2721 }
2722 }
2723 elsif( ref( $this ) && $self->_is_object( $this ) && $this->isa( 'HTML::Object::DOM::Element' ) )
2724 {
2725 my $elem = $this->isa_collection() ? $this->children->first : $this;
2726 my $found;
2727 if( $self->isa_collection() )
2728 {
2729 $self->children->for(sub
2730 {
2731 my( $i, $e ) = @_;
2732 if( $e->eid eq $elem->eid )
2733 {
2734 $found = $i;
2735 return;
2736 }
2737 });
2738 }
2739 else
2740 {
2741 return( $self->new_number( $self->eid eq $elem->eid ? 0 : -1 ) );
2742 }
2743 }
2744 }
2745 # Return the position of the element or if this is a collection, the position of the first element in the collection
2746 else
2747 {
2748 my $elem = ( $self->isa_collection ? $self->children->first : $self );
2749 return( $self->new_number(-1) ) if( !defined( $elem ) || !CORE::length( $elem ) );
2750 return( $self->new_number(0) ) if( !$elem->parent );
2751 my $pos = $elem->parent->children->pos( $elem );
2752 return( $self->new_number( defined( $pos ) ? $pos : -1 ) );
2753 }
2754 }
2755  
2756 sub insertAfter { return( shift->_insert_before_after( @_, { action => 'after' }) ); }
2757  
2758 sub insertBefore { return( shift->_insert_before_after( @_, { action => 'before' }) ); }
2759  
2760 # Takes a selector; or
2761 # an element object; or
2762 # a collection object; or
2763 # a code reference and
2764 # return true or false object
2765 # "Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments."
2766 # <https://api.jquery.com/is/#is-selector>
2767 sub is
2768 {
2769 my $self = shift( @_ );
2770 my $this = shift( @_ );
2771 my $found = $self->false;
2772 if( ref( $this ) CORE::eq 'CODE' )
2773 {
2774 if( $self->isa_collection() )
2775 {
2776 $self->children->for(sub
2777 {
2778 my( $i, $e ) = @_;
2779 local $_ = $e;
2780 if( $this->( $i, $e ) )
2781 {
2782 $found = $self->true;
2783 return(1);
2784 }
2785 });
2786 }
2787 else
2788 {
2789 my $pos = ( $self->parent ? $self->parent->children->pos( $self ) : 0 );
2790 if( $this->( $pos, $self ) )
2791 {
2792 $found = $self->true;
2793 }
2794 }
2795 return( $found );
2796 }
2797 elsif( ref( $this ) && $self->_is_object( $this ) && $this->isa( 'HTML::Object::DOM::Element' ) )
2798 {
2799 my $a = $this->isa_collection() ? $this->children() : $self->new_array( [ $this ] );
2800 if( $self->isa_collection() )
2801 {
2802 my $kids = $self->children;
2803 $kids->foreach(sub
2804 {
2805 my $e = shift( @_ );
2806 $a->foreach(sub
2807 {
2808 my $other = shift( @_ );
2809 if( $e->eid CORE::eq $other->eid )
2810 {
2811 $found = $self->true;
2812 # Exit this loop and tell the upper loop to exit as well
2813 return( $kids->return( undef() ) );
2814 }
2815 });
2816 });
2817 }
2818 else
2819 {
2820 $a->foreach(sub
2821 {
2822 if( $_->eid CORE::eq $self->eid )
2823 {
2824 $found = $self->true;
2825 return(1);
2826 }
2827 });
2828 }
2829 return( $found );
2830 }
2831 # Works for xpath, but also need to account for special keywords starting with ':'
2832 # e.g.:
2833 # is( ":first-child" )
2834 # is( ":contains('Peter')" )
2835 # is( ":checked" )
2836 elsif( !ref( $this ) ||
2837 ( ref( $this ) && overload::Overloaded( $this ) && overload::Method( $this, '""' ) ) )
2838 {
2839 my $xpath = $self->_xpath_value( $this );
2840 # false() method is inherited from Module::Generic module.
2841 if( $self->isa_collection() )
2842 {
2843 $self->children->foreach(sub
2844 {
2845 if( $_->matches( $xpath ) )
2846 {
2847 $found = $self->true;
2848 return(1);
2849 }
2850 });
2851 }
2852 else
2853 {
2854 $found = $self->true if( $self->matches( $xpath ) );
2855 }
2856 return( $found );
2857 }
2858 else
2859 {
2860 return( $self->error( "I was expecting a selector, an element object, a collection object or a code reference, but got '$this'." ) );
2861 }
2862 }
2863  
2864 sub isArray { return( shift->_is_array( @_ ) ); }
2865  
2866 sub isa_collection
2867 {
2868 my $self = shift( @_ );
2869 if( scalar( @_ ) )
2870 {
2871 return( $_[0]->isa( 'HTML::Object::Collection' ) );
2872 }
2873 return( $self->isa( 'HTML::Object::Collection' ) );
2874 }
2875  
2876 sub isa_element
2877 {
2878 my $self = shift( @_ );
2879 my $e = scalar( @_ ) ? shift( @_ ) : $self;
2880 return( $self->_is_a( $e, 'HTML::Object::DOM::Element' ) );
2881 }
2882  
2883 sub length
2884 {
2885 my $self = shift( @_ );
2886 if( $self->isa_collection )
2887 {
2888 return( $self->children->length );
2889 }
2890 else
2891 {
2892 return( $self->new_number(1) );
2893 }
2894 }
2895  
2896 # $e->load( 'https://example.org/some/where' );
2897 # $e->load( 'https://example.org/some/where', { param1 => value1, param2 => value2 } );
2898 # $e->load( 'https://example.org/some/where', { param1 => value1, param2 => value2 }, sub
2899 # {
2900 # my( $responseText, $responseStatus, $responseObject ) = @_;
2901 # # do something
2902 # });
2903 # <https://api.jquery.com/load/#load-url-data-complete>
2904 # $e->load( 'https://example.org/some/where', sub
2905 # {
2906 # my( $responseText, $responseStatus, $responseObject ) = @_;
2907 # # do something
2908 # });
2909 # $e->load({
2910 # url => 'https://example.org/some/where',
2911 # data => { param1 => value1, param2 => value2 },
2912 # callback => sub
2913 # {
2914 # my( $responseText, $responseStatus, $responseObject ) = @_;
2915 # # do something
2916 # }
2917 # });
2918 # <https://api.jquery.com/load/#load-url-data-complete>
2919 sub load
2920 {
2921 my $self = shift( @_ );
2922 my( $url, $data, $complete ) = @_;
2923 my $opts = {};
2924 if( scalar( @_ ) == 1 && ref( $_[0] ) eq 'HASH' )
2925 {
2926 $opts = shift( @_ );
2927 ( $url, $data, $complete ) = @$opts{qw( url data callback )};
2928 }
2929 # e.g. $e->load( $url, $data, $complete, $options );
2930 elsif( scalar( @_ ) > 2 && ref( $_[-1] ) eq 'HASH' )
2931 {
2932 $opts = pop( @_ );
2933 }
2934  
2935 return( $self->error( "No url was provided to load data" ) ) if( !defined( $url ) || !CORE::length( "$url" ) );
2936 if( !defined( $complete ) && defined( $data ) && ref( $data ) eq 'CODE' )
2937 {
2938 $complete = $data;
2939 undef( $data );
2940 }
2941 if( defined( $data ) && ref( $data ) ne 'HASH' )
2942 {
2943 warn( "Data to be submitted to $url was provided, but I was expecting an hash reference and I got '", overload::StrVal( $data ), "'" ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
2944 return( $self->error( "Data to be submitted to $url was provided, but I was expecting an hash reference and I got '", overload::StrVal( $data ), "'" ) );
2945 }
2946 if( defined( $complete ) && ref( $complete ) ne 'CODE' )
2947 {
2948 return( $self->error( "A callback parameter was provided, and I was expecting a code reference, such as an anonymous subroutine, but instead I got '", overload::StrVal( $complete ), "'" ) );
2949 }
2950  
2951 # No need to go further if there is nothing in our collection
2952 my $children = $self->isa_collection ? $self->children : $self->new_array( $self );
2953 return( $self ) if( !$children->length );
2954 # if( !$children->length )
2955 # {
2956 # if( defined( $complete ) )
2957 # {
2958 # my $resp = HTTP::Response->new( 204, 'No content', [] );
2959 # $children->foreach(sub
2960 # {
2961 # $complete->( '', 'nocontent', $resp );
2962 # });
2963 # }
2964 # return( $self );
2965 # }
2966  
2967 # Ultimately, if the callback is not set, we set a dummy one instead
2968 $complete = sub{1} if( !defined( $complete ) );
2969  
2970 if( !$self->_load_class( 'HTTP::Promise', { version => 'v0.5.0' } ) )
2971 {
2972 return( $self->error( "HTTP::Promise version v0.5.0 or higher is required to use load()" ) );
2973 }
2974 if( !$self->_load_class( 'URI', { version => '1.74' } ) )
2975 {
2976 return( $self->error( "URI version 1.74 or higher is required to use load()" ) );
2977 }
2978 $opts->{timeout} //= 10;
2979 $opts->{agent} ||= "HTML::Object/$VERSION";
2980 # "If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded."
2981 # e.g.: $( "#new-projects" )->load( "/resources/load.html #projects li" );
2982 # <https://api.jquery.com/load/#load-url-data-complete>
2983 ( $url, my $target ) = split( /[[:blank:]\h]+/, $url, 2 );
2984  
2985 my $uri;
2986 # try-catch
2987 local $@;
2988 eval
2989 {
2990 $uri = URI->new( "$url" );
2991 };
2992 if( $@ )
2993 {
2994 return( $self->error( "Bad url provided \"$url\": $@" ) );
2995 }
2996  
2997 my $content;
2998 my $resp;
2999 my @http_options = qw(
3000 accept_encoding accept_language auto_switch_https cookie_jar dnt max_redirect
3001 proxy
3002 );
3003 my $params = {};
3004 foreach my $k ( @http_options )
3005 {
3006 if( exists( $opts->{ $k } ) &&
3007 defined( $opts->{ $k } ) &&
3008 CORE::length( $opts->{ $k } ) )
3009 {
3010 $params->{ $k } = $opts->{ $k };
3011 }
3012 }
3013 $params->{use_promise} = 0;
3014 # try-catch
3015 my $ua = HTTP::Promise->new( %$params );
3016 return( $self->pass_error( HTTP::Promise->error ) ) if( !defined( $ua ) );
3017  
3018 # Contextual URL that requires a base URL.
3019 # We check for documentURI of the root element, if any
3020 my( $doc_root, $doc_uri );
3021 if( ( substr( $uri, 0, 1 ) eq '/' ||
3022 substr( $uri, 0, 2 ) eq './' ||
3023 substr( $uri, 0, 3 ) eq '../' ) &&
3024 ( $doc_root = $self->getRootNode ) &&
3025 $doc_root->isa( 'HTML::Object::DOM::Document' ) &&
3026 ( $doc_uri = $doc_root->documentURI ) )
3027 {
3028 my $clone = $doc_uri->clone;
3029 $clone->path( $uri );
3030 $uri = $clone;
3031 }
3032  
3033 if( $uri->scheme eq 'http' || $uri->scheme eq 'https' )
3034 {
3035 # "The POST method is used if data is provided as an object; otherwise, GET is assumed."
3036 # <https://api.jquery.com/load/#load-url-data-complete>
3037 if( defined( $data ) )
3038 {
3039 $resp = $ua->post( $uri, $data, ( ref( $opts->{headers} ) eq 'HASH' && scalar( keys( %{$opts->{headers}} ) ) ) ? %{$opts->{headers}} : () );
3040 }
3041 else
3042 {
3043 $resp = $ua->get( $uri, ( ref( $opts->{headers} ) eq 'HASH' && scalar( keys( %{$opts->{headers}} ) ) ) ? %{$opts->{headers}} : () );
3044 }
3045  
3046 if( !$resp )
3047 {
3048 $self->_load_class( 'HTTP::Promise::Response' ) || return( $self->pass_error );
3049 my $err = "Error trying to get url \"${url}\": " . ( $ua->error ? $ua->error->message : 'unknown' );
3050 my $resp2 = HTTP::Promise::Response->new( 500, "Unexpected error", [], $err );
3051 $complete->( $err, 'error', $resp2, $ua );
3052 return( $self->error({
3053 code => 500,
3054 message => $err,
3055 }) );
3056 }
3057 $content = $resp->decoded_content;
3058  
3059 if( $resp->header( 'Client-Warning' ) || !$resp->is_success )
3060 {
3061 $complete->( $content, 'error', $resp, $ua );
3062 return( $self->error({
3063 code => $resp->code,
3064 message => $resp->message,
3065 }) );
3066 }
3067 }
3068 elsif( $uri->scheme eq 'file' )
3069 {
3070 $self->_load_class( 'HTTP::Promise::Response' ) || return( $self->pass_error );
3071 my $f = $self->new_file( $uri ) || return( $self->pass_error );
3072 if( $f->exists )
3073 {
3074 $resp = HTTP::Promise::Response->new( 200 => 'OK' );
3075 $content = $f->load;
3076 }
3077 else
3078 {
3079 my $resp2 = HTTP::Promise::Response->new( 404 => 'Not found' );
3080 my $err = "File $uri is not found.";
3081 $complete->( $err, 'error', $resp2, $ua );
3082 return( $self->error({
3083 code => 404,
3084 message => $err,
3085 }) );
3086 }
3087 }
3088 else
3089 {
3090 my $resp2 = HTTP::Promise::Response->new( 400 => 'Bad request' );
3091 my $err = "The URL provided is unsupported.";
3092 $complete->( $err, 'error', $resp2, $ua );
3093 return( $self->error({
3094 code => 400,
3095 message => $err,
3096 }) );
3097 }
3098  
3099 my $new;
3100 if( defined( $content ) && CORE::length( $content // '' ) )
3101 {
3102 my $parser = $self->new_parser;
3103 # HTML::Object::DOM::Document
3104 my $doc = $parser->parse_data( $content ) ||
3105 return( $self->pass_error( $parser->error ) );
3106 $new = $doc->children;
3107 # "When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded."
3108 if( defined( $target ) )
3109 {
3110 $doc->debug( $self->debug );
3111 my $elem = $doc->find( $target ) || return( $self->pass_error( $doc->error ) );
3112 # $new = $self->new_array( $elem );
3113 $new = $elem->children;
3114 }
3115 }
3116 # The content returned is empty, so we cannot parse it, and instead we provide a HTML::Object::DOM::Text element with an empty value inside.
3117 else
3118 {
3119 my $txt = $self->new_text( value => '' ) || return( $self->pass_error );
3120 $new = $self->new_array( $txt );
3121 }
3122  
3123 # "If a "complete" callback is provided, it is executed after post-processing and HTML insertion has been performed. The callback is fired once for each element in the collection, and $_ is set to each DOM element in turn."
3124 $children->foreach(sub
3125 {
3126 my $child = shift( @_ );
3127 # Make a deep copy for each child element and set each child element's children
3128 my $clone = $new->map(sub{ $_->clone });
3129 $child->children( $clone );
3130 $child->reset(1);
3131 my $status = 'error';
3132 if( $resp->code >= 200 && $resp->code < 300 )
3133 {
3134 $status = 'success';
3135 }
3136 elsif( $resp->code == 304 )
3137 {
3138 $status = 'notmodified';
3139 }
3140 elsif( $resp->is_error )
3141 {
3142 $status = 'error';
3143 }
3144 $complete->( $content, $status, $resp );
3145 });
3146 return( $self );
3147 }
3148  
3149 sub map
3150 {
3151 my $self = shift( @_ );
3152 my $code = shift( @_ ) || return( $self->error( "No code reference was provided." ) );
3153 return( $self->error( "I was expecting a code reference, but instead I was provided with this: \"", overload::StrVal( $code ), "\"." ) ) if( ref( $code ) ne 'CODE' );
3154 return( $self->children->for( $code ) );
3155 }
3156  
3157 sub matches
3158 {
3159 my( $self, $path ) = @_;
3160 return( $self->xp->matches( $self, $path, $self ) );
3161 }
3162  
3163 sub name { return( shift->attr( name => shift( @_ ) ) ); }
3164  
3165 sub new_attribute
3166 {
3167 my $self = shift( @_ );
3168 my $opts = $self->_get_args_as_hash( @_ );
3169 $opts->{debug} = $self->debug unless( exists( $opts->{debug} ) );
3170 my $e = HTML::Object::DOM::Attribute->new( $opts ) ||
3171 return( $self->pass_error( HTML::Object::DOM::Attribute->error ) );
3172 return( $e );
3173 }
3174  
3175 sub new_parser { HTML::Object::DOM->new }
3176  
3177 sub new_collection
3178 {
3179 my $self = shift( @_ );
3180 my $opts = $self->_get_args_as_hash( @_ );
3181 $opts->{debug} = $self->debug unless( exists( $opts->{debug} ) );
3182 $opts->{end} = $self unless( exists( $opts->{end} ) );
3183 my $e = HTML::Object::Collection->new( $opts ) ||
3184 return( $self->pass_error( HTML::Object::Collection->error ) );
3185 return( $e );
3186 }
3187  
3188 sub new_root
3189 {
3190 my $self = shift( @_ );
3191 my $opts = $self->_get_args_as_hash( @_ );
3192 $opts->{debug} = $self->debug unless( exists( $opts->{debug} ) );
3193 my $e = HTML::Object::DOM::Root->new( $opts ) ||
3194 return( $self->pass_error( HTML::Object::DOM::Root->error ) );
3195 return( $e );
3196 }
3197  
3198 sub normalize_content
3199 {
3200 my $self = shift( @_ );
3201 if( $self->isa_collection )
3202 {
3203 $self->children->foreach(sub
3204 {
3205 $_->normalize_content;
3206 });
3207 return( $self );
3208 }
3209 else
3210 {
3211 $self->SUPER::normalize_content;
3212 }
3213 }
3214  
3215 # Takes a selector expression; or
3216 # a element object; or
3217 # a collection of elements; or
3218 # an array of element objects to match against the set.
3219 sub not
3220 {
3221 my $self = shift( @_ );
3222 my $this;
3223 $this = shift( @_ ) if( scalar( @_ ) );
3224 my $collection = $self->new_collection( end => $self );
3225 # Process array of elements
3226 my $process;
3227 $process = sub
3228 {
3229 my( $kids, $to_exclude ) = @_;
3230 my $exclude = $self->new_array;
3231 $kids->foreach(sub
3232 {
3233 my $elem = shift( @_ );
3234 my $path = $elem->getNodePath();
3235 $to_exclude->foreach(sub
3236 {
3237 my $e = shift( @_ );
3238 return(1) if( !$self->_is_object( $e ) || !$e->isa( 'HTML::Object::DOM::Element' ) );
3239 return(1) if( !$e->isa( 'HTML::Object::DOM::Comment' ) || $e->isa( 'HTML::Object::DOM::Text' ) || $e->isa( 'HTML::Object::DOM::Declaration' ) || $e->isa( 'HTML::Object::DOM::Space' ) );
3240 # This element matches the xpath of one of the collection element, so we exclude it from the result
3241 if( $e->matches( $path ) )
3242 {
3243 $exclude->push( $elem );
3244 return(1);
3245 }
3246 });
3247 });
3248 return( $kids->clone->remove( $exclude ) );
3249 };
3250  
3251 # No parameter provided, thus we return an empty collection
3252 if( !defined( $this ) )
3253 {
3254 return( $collection );
3255 }
3256 elsif( !ref( $this ) || ( $self->_is_object( $this ) && overload::Overloaded( $this ) && overload::Method( '""' ) ) )
3257 {
3258 my $xpath = $self->_xpath_value( "$this" );
3259 my $doc = $self->filter(sub
3260 {
3261 my $elem = shift( @_ );
3262 # try-catch
3263 my $rv = eval
3264 {
3265 return( !$elem->matches( $xpath ) );
3266 };
3267 if( $@ )
3268 {
3269 return( $self->error( "Caught an exception while calling matches with xpath '$xpath' for element of class ", ref( $elem ), " and tag '", $elem->tag, "': $@" ) );
3270 }
3271 return( $rv );
3272 });
3273 $collection->children( $doc->children );
3274 }
3275 elsif( $self->_is_array( $this ) )
3276 {
3277 $this = $self->new_array( $this );
3278 #my $new = $self->children->clone->remove( $this );
3279 #$collection->children( $new );
3280 $this->unique(1);
3281 my $new = $process->( $self->children, $this );
3282 $collection->children( $new );
3283 }
3284 elsif( $self->_is_object( $this ) && $self->isa_collection( $this ) )
3285 {
3286 my $kids = $this->children;
3287 my $new = $process->( $self->children, $kids );
3288 $collection->children( $new );
3289 }
3290 elsif( $self->_is_object( $this ) && $this->isa( 'HTML::Object::DOM::Element' ) )
3291 {
3292 $this = $self->new_array( [ $this ] );
3293 my $new = $process->( $self->children, $this );
3294 $collection->children( $new );
3295 }
3296 else
3297 {
3298 return( $self->error( "I receive an object \"", ref( $this ), "\", but I do not know what to do with it." ) );
3299 }
3300 return( $collection );
3301 }
3302  
3303 # Returns a new collection of elements whose position is an even number
3304 sub odd
3305 {
3306 my $self = shift( @_ );
3307 return( $self ) unless( $self->isa_collection );
3308 my $odd = $self->children->odd;
3309 my $collection = $self->new_collection;
3310 $collection->children( $odd );
3311 return( $collection );
3312 }
3313  
3314 # Takes html string (start with <tag...), text object (HTML::Object::DOM::Text), array or element object
3315 # or alternatively a code reference that returns the above
3316 sub prepend { return( shift->_append_prepend( @_, { action => 'prepend' } ) ); }
3317  
3318 sub prependTo { return( shift->_append_prepend_to( @_, { action => 'prepend' } ) ); }
3319  
3320 # TODO: prop(), e.g. $e->prop('outerHTML') or $e->prop('tagName')
3321 sub prop
3322 {
3323 my $self = shift( @_ );
3324 # In get mode, this only affects the first element of the set
3325 # In set mode, this affect all elements of the set
3326 # <https://api.jquery.com/prop/#prop-propertyName>
3327 # <https://developer.mozilla.org/en-US/docs/Web/API/Element#properties>
3328 my $map =
3329 {
3330 checked => sub{ return( shift->attr( 'checked' ) ); },
3331 # Returns the number of child elements of this element.
3332 childElementCount => sub{ return( shift->children->length ); },
3333 # Returns the child elements of this element.
3334 children => sub{ return( shift->children ); },
3335 # Is a DOMString representing the class of the element.
3336 className => sub{ return( shift->attr( 'class' ) ); },
3337 disabled => sub{ return( shift->attr( 'disabled' ) ); },
3338 # Returns the first child element of this element.
3339 firstElementChild => sub{ return( shift->children->first ); },
3340 # Is a DOMString representing the id of the element.
3341 id => sub{ return( shift->attr( 'id' ) ); },
3342 # Is a DOMString representing the markup of the element's content.
3343 innerHTML => sub
3344 {
3345 my $e = shift( @_ );
3346 my $a = $self->new_array;
3347 $self->children->foreach(sub
3348 {
3349 my $e = shift( @_ );
3350 my $v = $e->as_string;
3351 $a->push( defined( $v ) ? $v->scalar : $v );
3352 });
3353 return( $a->join( '' ) );
3354 },
3355 # Returns the last child element of this element.
3356 lastElementChild => sub{ return( shift->children->last ); },
3357 # A DOMString representing the local part of the qualified name of the element.
3358 localName => sub{ return( shift->tag ); },
3359 # Is an Element, the element immediately following the given one in the tree, or null if there's no sibling node.
3360 nextElementSibling => sub
3361 {
3362 my $e = shift( @_ );
3363 my $parent = $e->parent || return;
3364 my $pos = $parent->children->pos( $e );
3365 return( $parent->children->index( $pos + 1 ) );
3366 },
3367 # Is a DOMString representing the markup of the element including its content. When used as a setter, replaces the element with nodes parsed from the given string.
3368 outerHTML => sub{ return( shift->as_string ); },
3369 # Is a Element, the element immediately preceding the given one in the tree, or null if there is no sibling element.
3370 previousElementSibling => sub
3371 {
3372 my $e = shift( @_ );
3373 my $parent = $e->parent || return;
3374 my $pos = $parent->children->pos( $e );
3375 return( $parent->children->index( $pos - 1 ) );
3376 },
3377 readonly => sub{ return( shift->attr( 'readonly' ) ); },
3378 # Returns a String with the name of the tag for the given element.
3379 tagName => sub{ return( shift->tag ); },
3380 };
3381 my $ro = $self->new_array( [qw(
3382 childelementcount children firstelementchild
3383 )] );
3384  
3385 # Get
3386 if( scalar( @_ ) == 1 )
3387 {
3388 my $e = $self->isa_collection ? $self->children->first : $self;
3389 return if( !$e );
3390 my $prop = lc( shift( @_ ) );
3391 return( $self->error( "No such property \"$prop\"." ) ) if( !CORE::exists( $map->{ $prop } ) );
3392 my $code = $map->{ $prop };
3393 return( $code->( $e ) );
3394 }
3395 # Set
3396 elsif( scalar( @_ ) > 1 )
3397 {
3398 my $all = $self->new_array( $self->isa_collection ? $self->children : [ $self ] );
3399 my @props = @_;
3400 while( scalar( @props ) )
3401 {
3402 my( $prop, $val ) = CORE::splice( @props, 0, 2 );
3403 $prop = lc( $prop );
3404 if( defined( $val ) && CORE::length( $val ) && $ro->exists( $prop ) )
3405 {
3406 next;
3407 }
3408  
3409 # process the html
3410 if( $prop eq 'innerHTML' )
3411 {
3412 if( defined( $val ) )
3413 {
3414 my $p = HTML::Object::DOM->new;
3415 my $doc = $p->parse_data( $val ) || do
3416 {
3417 $! = $p->error;
3418 return;
3419 };
3420 $all->foreach(sub
3421 {
3422 my $e = shift( @_ );
3423 $e->children( $doc->children );
3424 $e->reset(1);
3425 });
3426 }
3427 else
3428 {
3429 $all->foreach(sub
3430 {
3431 my $e = shift( @_ );
3432 $e->children->empty;
3433 $e->reset(1);
3434 });
3435 }
3436 next;
3437 }
3438 elsif( $prop eq 'outerHTML' )
3439 {
3440 if( defined( $val ) )
3441 {
3442 my $p = HTML::Object::DOM->new;
3443 my $doc = $p->parse_data( $val ) || do
3444 {
3445 $! = $p->error;
3446 return;
3447 };
3448 $all->foreach(sub
3449 {
3450 my $e = shift( @_ );
3451 my $parent = $e->parent;
3452 return(1) if( !$parent );
3453 my $pos = $parent->children->pos( $e );
3454 my @new = ();
3455 $doc->children->foreach(sub
3456 {
3457 my $kid = shift( @_ );
3458 my $clone = $kid->clone;
3459 $clone->parent( $parent );
3460 push( @new, $clone );
3461 });
3462 $parent->children->splice( $pos, 1, @new );
3463 $parent->reset(1);
3464 });
3465 }
3466 else
3467 {
3468 $all->foreach(sub
3469 {
3470 my $e = shift( @_ );
3471 my $parent = $e->parent;
3472 return(1) if( !$parent );
3473 my $pos = $parent->children->pos( $e );
3474 $e->children->splice( $pos, 1 );
3475 $e->reset(1);
3476 });
3477 }
3478 next;
3479 }
3480  
3481 $all->foreach(sub
3482 {
3483 my $e = shift( @_ );
3484 if( $prop eq 'checked' )
3485 {
3486 if( $val )
3487 {
3488 $e->attr( checked => 'checked' );
3489 }
3490 else
3491 {
3492 $e->attributes->delete( $prop );
3493 }
3494 $e->reset(1);
3495 }
3496 elsif( $prop eq 'className' )
3497 {
3498 if( defined( $val ) )
3499 {
3500 $e->attr( class => $val );
3501 }
3502 else
3503 {
3504 $e->attributes->delete( 'class' );
3505 }
3506 $e->reset(1);
3507 }
3508 elsif( $prop eq 'disabled' )
3509 {
3510 if( $val )
3511 {
3512 $e->attr( disabled => 'disabled' );
3513 }
3514 else
3515 {
3516 $e->attributes->delete( $prop );
3517 }
3518 $e->reset(1);
3519 }
3520 elsif( $prop eq 'id' )
3521 {
3522 if( defined( $val ) )
3523 {
3524 $e->attr( id => $val );
3525 }
3526 else
3527 {
3528 $e->attributes->delete( $prop );
3529 }
3530 $e->reset(1);
3531 }
3532 elsif( $prop eq 'readonly' )
3533 {
3534 if( $val )
3535 {
3536 $e->attr( readonly => 'readonly' );
3537 }
3538 else
3539 {
3540 $e->attributes->delete( $prop );
3541 }
3542 $e->reset(1);
3543 }
3544 });
3545 }
3546 }
3547 }
3548  
3549 sub promise
3550 {
3551 my $self = shift( @_ );
3552 return( Promise::Me->new( @_ ) );
3553 # my $deferred = Promise::XS::deferred();
3554 # return( $deferred->promise() );
3555 }
3556  
3557 # NOTE: queue is not implemented
3558 # <https://api.jquery.com/queue/>
3559  
3560 sub rank { return( shift->_set_get_number_as_object( 'rank', @_ ) ); }
3561  
3562 # <https://api.jquery.com/remove/>
3563 # TODO: Need to check again and do some test to ensure this api is compliant
3564 sub remove
3565 {
3566 my $self = shift( @_ );
3567 if( $self->isa_collection )
3568 {
3569 $self->children->foreach(sub
3570 {
3571 my $e = shift( @_ );
3572 my $pos = $e->pos;
3573 my $parent = $e->parent;
3574 $e->delete;
3575 });
3576 }
3577 # xpath provided
3578 elsif( @_ )
3579 {
3580 my $xpath = $self->_xpath_value( shift( @_ ) ) || return;
3581 $self->find( $xpath )->remove;
3582 }
3583 # Equivalent to delete
3584 else
3585 {
3586 $self->delete;
3587 }
3588 return( $self );
3589 }
3590  
3591 sub removeAttr
3592 {
3593 my $self = shift( @_ );
3594 my $attr = shift( @_ );
3595 return( $self ) if( !defined( $attr ) );
3596 if( $self->isa_collection )
3597 {
3598 $self->children->foreach(sub
3599 {
3600 $_->attributes->delete( $attr );
3601 $_->reset(1);
3602 });
3603 }
3604 else
3605 {
3606 $self->attributes->delete( $attr );
3607 $self->reset(1);
3608 }
3609 return( $self );
3610 }
3611  
3612 # class name, array of class name or a code reference
3613 # If parameter is a code reference it must return a class name or an array of class name
3614 # It receives "the index position of the element in the set and the old class value as arguments"
3615 sub removeClass
3616 {
3617 my $self = shift( @_ );
3618 my $this;
3619 $this = shift( @_ ) if( @_ );
3620 my $a;
3621 # No class provided, so we will remove all existing class
3622 if( !defined( $this ) )
3623 {
3624 $a = $self->new_array;
3625 }
3626 elsif( $self->_is_array( $this ) )
3627 {
3628 $a = $self->new_array( $this );
3629 my $failed = 0;
3630 $a->foreach(sub
3631 {
3632 if( ref( $_ ) && !( overload::Overloaded( $_ ) && overload::Method( $_, '""' ) ) )
3633 {
3634 $failed++;
3635 $self->error( "Class provided to be removed \"$_\" is not a string nor an overloaded object." );
3636 return(0);
3637 }
3638 });
3639 return( $self ) if( $failed );
3640 }
3641  
3642 my $process;
3643 $process = sub
3644 {
3645 my $e = shift( @_ );
3646 return( $e ) unless( $e->attributes->exists( 'class' ) );
3647 my $c = $self->new_array( [split( /[[:blank:]\h]+/, $e->attributes->get( 'class' ) )] );
3648 # Loop through the element classes
3649 $c->for(sub
3650 {
3651 my( $i, $v ) = @_;
3652 if( ref( $this ) CORE::eq 'CODE' )
3653 {
3654 local $_ = $self;
3655 my $res = $this->( $i, $v );
3656 if( $self->_is_array( $res ) )
3657 {
3658 $a = $self->new_array( $res );
3659 }
3660 else
3661 {
3662 $a = $self->new_array( [ $res ] );
3663 }
3664 }
3665 $a->foreach(sub
3666 {
3667 my $to_remove = shift( @_ );
3668 if( $v CORE::eq "$to_remove" )
3669 {
3670 $c->splice( $i, 1 );
3671 $c->return( -1 );
3672 }
3673 return;
3674 });
3675 });
3676 $e->reset(1);
3677 return(1);
3678 };
3679 if( $self->isa_collection )
3680 {
3681 $self->children->foreach( $process );
3682 }
3683 else
3684 {
3685 $process->( $self );
3686 }
3687 return( $self );
3688 }
3689  
3690 sub removeData
3691 {
3692 my $self = shift( @_ );
3693 my $elem;
3694 if( $self->isa_collection )
3695 {
3696 $elem = $self->children->first;
3697 }
3698 elsif( !$self->_is_a( $self => 'HTML::Object::DOM::Element' ) )
3699 {
3700 return( $self->error( "You can only call the removeData() method on html elements." ) );
3701 }
3702 else
3703 {
3704 $elem = $self;
3705 }
3706  
3707 my $keys;
3708 # If no @_ is provided this is undef and it is ok, we would remove all data attributes then
3709 if( @_ )
3710 {
3711 my $this = shift( @_ );
3712 if( $self->_is_empty( $this ) )
3713 {
3714 return( $self->error( "Data name value provided is empty. If you want to remove all data attributes, simply call removeData() without argument." ) );
3715 }
3716 elsif( !ref( $this ) ||
3717 ( ref( $this ) && $self->_can_overload( $this => '""' ) ) )
3718 {
3719 $this = "$this";
3720 if( CORE::index( $this, ' ' ) != -1 )
3721 {
3722 $keys = [CORE::split( /[[:blank:]\h]+/, $this )];
3723 }
3724 else
3725 {
3726 $keys = [$this];
3727 }
3728 }
3729 elsif( $self->_is_array( $this ) )
3730 {
3731 $keys = $this;
3732 }
3733 else
3734 {
3735 return( $self->error( "Data name value to remove is unsupported. You can only provide a string, a space-separated string of names, or an array reference." ) );
3736 }
3737 }
3738 else
3739 {
3740 $keys = $elem->attributes_sequence;
3741 }
3742  
3743 my $changed = 0;
3744 foreach my $k ( @$keys )
3745 {
3746 if( $elem->hasAttribute( 'data-' . $k ) )
3747 {
3748 $elem->removeAttribute( 'data-' . $k );
3749 $changed++;
3750 }
3751 }
3752 $elem->reset(1) if( $changed );
3753 # Return undef
3754 return;
3755 }
3756  
3757 # Takes html string, array of elements, an element (including a collection object) or a code reference
3758 sub replaceWith
3759 {
3760 my $self = shift( @_ );
3761 my $this = shift( @_ ) || return( $self->error( "Nothing was provided to replace." ) );
3762 my $a;
3763 if( !ref( $this ) )
3764 {
3765 my $p = $self->new_parser;
3766 $this = $p->parse_data( $this ) || return( $self->pass_error( $p->error ) );
3767 $a = $self->new_array( [ $this ] );
3768 }
3769 elsif( $self->_is_array( $this ) )
3770 {
3771 # Make sure this is a Module::Generic::Array object
3772 $a = $self->new_array( $this );
3773 }
3774 elsif( $self->_is_object( $this ) )
3775 {
3776 return( $self->error( "Object provided '$this' (", overload::StrVal( $this ), ") is not an HTML::Object::DOM::Element object." ) ) if( !$this->isa( 'HTML::Object::DOM::Element' ) );
3777 $a = $self->new_array( [ $this ] );
3778 }
3779 elsif( ref( $this ) ne 'CODE' )
3780 {
3781 return( $self->error( "I do not know what to do with '$this'. I was expecing an html string, or an HTML::Object::DOM::Element or an array of element objects or a collection object (HTML::Object::Collection) or a code reference." ) );
3782 }
3783  
3784 if( $self->isa_collection )
3785 {
3786 my $failed = 0;
3787 $self->children->foreach(sub
3788 {
3789 my $elem = shift( @_ );
3790 if( ref( $this ) CORE::eq 'CODE' )
3791 {
3792 local $_ = $elem;
3793 my $res = $this->( $elem );
3794 if( !defined( $res ) )
3795 {
3796 $failed++;
3797 $self->error( "An error occurred while executing code reference to replace html element(s). Code reference returned undef." );
3798 return(0);
3799 }
3800 if( $self->_is_object( $res ) && $res->isa( 'HTML::Object::DOM::Element' ) )
3801 {
3802 $a = $self->new_array( [ $res ] );
3803 }
3804 elsif( overload::Overloaded( $res ) && overload::Method( $res, '""' ) )
3805 {
3806 my $elem = $self->new_parser( "$res" );
3807 if( !defined( $elem ) )
3808 {
3809 $failed++;
3810 return(0);
3811 }
3812 $a = $self->new_array( [ $elem ] );
3813 }
3814 else
3815 {
3816 $failed++;
3817 $self->error( "Value returned from code reference to be used in replaceWith is neither a string nor a HTML::Object::DOM::Element, so I do not know what to do with it." );
3818 return(0);
3819 }
3820 }
3821 if( !$elem->parent )
3822 {
3823 $self->error( "Found an element within a collection that has no parent! Element has tag \"", $elem->tag, "\"." );
3824 return(0);
3825 }
3826 my $pos = $elem->parent->pos( $elem );
3827 if( !defined( $pos ) )
3828 {
3829 $self->error( "This element with tag \"", $self->tag, "\" has a parent and yet I could not find its position." );
3830 return(0);
3831 }
3832 my $new = $self->new_array;
3833 $a->foreach(sub
3834 {
3835 my $e = $_->detach->clone();
3836 $e->parent( $elem->parent );
3837 $new->push( $e );
3838 });
3839 $elem->parent->children->splice( $pos, 1, $a->list );
3840 $elem->parent->reset(1);
3841 });
3842 # Now that the element have been copied to their replacement location, we remove them
3843 $a->foreach(sub
3844 {
3845 $_->delete;
3846 });
3847 return if( $failed );
3848 }
3849 else
3850 {
3851 if( ref( $this ) CORE::eq 'CODE' )
3852 {
3853 local $_ = $self;
3854 my $res = $this->( $self );
3855 return( $self->error( "An error occurred while executing code reference to replace html element(s). Code reference returned undef." ) ) if( !defined( $res ) );
3856 if( $self->_is_object( $res ) && $res->isa( 'HTML::Object::DOM::Element' ) )
3857 {
3858 $a = $self->new_array( [ $res ] );
3859 }
3860 elsif( overload::Overloaded( $res ) && overload::Method( $res, '""' ) )
3861 {
3862 my $elem = $self->new_parser( "$res" );
3863 return if( !defined( $elem ) );
3864 $a = $self->new_array( [ $elem ] );
3865 }
3866 else
3867 {
3868 return( $self->error( "Value returned from code reference to be used in replaceWith is neither a string nor a HTML::Object::DOM::Element, so I do not know what to do with it." ) );
3869 }
3870 }
3871  
3872 # Object has no parent, so we are essentially replace 1 element for one or more others with no attachment to the dom
3873 if( !$self->parent )
3874 {
3875 # Basically swapping one element for another
3876 if( $a->length == 1 )
3877 {
3878 my $e = $a->first;
3879 $e->detach;
3880 return( $e );
3881 }
3882 # There are multiple element, create a document element
3883 else
3884 {
3885 my $doc = HTML::Object::DOM::Document->new;
3886 $doc->children( $a );
3887 $a->foreach(sub
3888 {
3889 $_->detach;
3890 $_->parent( $doc );
3891 $_->parent->reset(1);
3892 });
3893 return( $doc );
3894 }
3895 }
3896 else
3897 {
3898 my $pos = $self->parent->pos( $self );
3899 return( $self->error( "This element with tag \"", $self->tag, "\" has a parent and yet I could not find its position." ) ) if( !defined( $pos ) );
3900 $a->foreach(sub
3901 {
3902 $_->detach->parent( $self->parent );
3903 });
3904 $self->parent->children->splice( $pos, 1, $a->list );
3905 $self->parent->reset(1);
3906 }
3907 }
3908 return( $self );
3909 }
3910  
3911 sub set_namespace
3912 {
3913 my $self = shift( @_ );
3914 return( $self->xp->new->set_namespace( @_ ) );
3915 }
3916  
3917 # Since this is a perl context, this only set the inline css 1) back to its previous value,
3918 # if any; or 2) remove the display property if there was no previous value set.
3919 # Any parameter provided will be ignored
3920 # See the hide() method for its alter ego.
3921 sub show
3922 {
3923 my $self = shift( @_ );
3924 my( $this, $code ) = @_;
3925 $code = $this if( ref( $this ) eq 'CODE' && !defined( $code ) );
3926 my $process;
3927 $process = sub
3928 {
3929 my $e = shift( @_ );
3930 my $internal = $e->internal;
3931 my $rule = $self->_css_object();
3932 if( defined( $rule ) )
3933 {
3934 my $display = $rule->get_property_by_name( 'display' );
3935 my $val = $display->value;
3936 # if display current value is 'none', we check if there was a previous value we kept
3937 # and if there is we restore it, otherwise we simply just remove the property
3938 if( $val eq 'none' )
3939 {
3940 my $previous_val = $internal->{css_display_value};
3941 if( defined( $previous_val ) && CORE::length( $previous_val ) )
3942 {
3943 $display->value( $previous_val );
3944 }
3945 else
3946 {
3947 $display->remove_from( $rule );
3948 }
3949 }
3950 }
3951 # otherwise, there is no rule inline defined, and thus, nothing to do.
3952  
3953 # Is there any rule and properties to save back?
3954 if( defined( $rule ) && $rule->elements->length > 0 )
3955 {
3956 $e->_css_object( $rule );
3957 }
3958 };
3959  
3960 if( $self->isa_collection )
3961 {
3962 $self->children->foreach(sub
3963 {
3964 $process->( $_ );
3965 $_->reset(1);
3966 });
3967 }
3968 elsif( $self->tag->substr( 0, 1 ) eq '_' )
3969 {
3970 return( $self->error( "You can only use the hide() or show() method on html object elements. The element you are calling hide() with is an object of class \"", ref( $self ), "\"." ) );
3971 }
3972 else
3973 {
3974 $process->( $self );
3975 $self->reset(1);
3976 }
3977 }
3978  
3979 # This is here and although it has been deprecated, so that $.uniqueSort() works
3980 # <https://stackoverflow.com/questions/63575333/javascript-replacement-of-sourceindex-in-chromium-browsers>
3981 # <https://developer.mozilla.org/en-US/docs/Web/API/Document/all>
3982 sub sourceIndex : lvalue { return( shift->_set_get_lvalue( 'sourceIndex', @_ ) ); }
3983  
3984 sub string_value
3985 {
3986 my $self = shift( @_ );
3987 return( $self->value ) if( $self->isCommentNode );
3988 return( $self->as_text );
3989 }
3990  
3991 # This is normally a HTML::Object::DOM::Element property and it should not be used equally
3992 # by a collection object, because of its nature, so we created it here to catch calls to it
3993 # while still allowing HTML::Object::DOM::Element to use it normally
3994 sub tag
3995 {
3996 my $self = shift( @_ );
3997 if( @_ )
3998 {
3999 if( $self->isa_collection )
4000 {
4001 return( $self->error( "tag is a read-only property" ) );
4002 }
4003 else
4004 {
4005 return( $self->_set_get_scalar_as_object( 'tag', @_ ) );
4006 }
4007 }
4008 else
4009 {
4010 if( $self->isa_collection )
4011 {
4012 my $first = $self->children->first;
4013 return unless( $first && $self->_is_a( $first, 'HTML::Object::DOM::Element' ) );
4014 return( $first->_set_get_scalar_as_object( 'tag' ) );
4015 }
4016 else
4017 {
4018 return( $self->_set_get_scalar_as_object( 'tag' ) );
4019 }
4020 }
4021 }
4022  
4023 sub tagname
4024 {
4025 my $self = shift( @_ );
4026 my @args = @_;
4027 my $map =
4028 {
4029 Comment => '#comment',
4030 Text => '#text'
4031 };
4032 my $a = $self->new_array;
4033 $self->children->foreach(sub
4034 {
4035 my $e = shift( @_ );
4036 my $type = [split( /::/, ref( $e ) )]->[-1];
4037 $a->push( exists( $map->{ $type } ) ? $map->{ $type } : $e->tag( @args ) );
4038 });
4039 return( $a );
4040 }
4041  
4042 # This method work for absolutely any element, including the root element (html)
4043 sub text
4044 {
4045 my $self = shift( @_ );
4046 my $this = shift( @_ );
4047 # Mutator
4048 if( defined( $this ) )
4049 {
4050 if( !ref( $this ) ||
4051 ( ref( $this ) && overload::Overloaded( $this ) && overload::Method( $this, '""' ) ) )
4052 {
4053 $this = "$this";
4054 }
4055 elsif( ref( $this ) ne 'CODE' )
4056 {
4057 return( $self->error( "I was expecting some text data or a code reference in replacement of text for this element \"", $self->tag, "\", but instead got '$this'." ) );
4058 }
4059  
4060 my $is_code = ref( $this ) eq 'CODE' ? 1 : 0;
4061 my $process = sub
4062 {
4063 my( $e, $i ) = @_;
4064 if( $is_code )
4065 {
4066 my $current_text = $e->as_text( unescape => 1 );
4067 my $text = $this->( $i, $current_text );
4068 if( !defined( $text ) || !CORE::length( $text ) )
4069 {
4070 $e->empty();
4071 # Next please
4072 return(1);
4073 }
4074 elsif( ref( $text ) &&
4075 !( overload::Overloaded( $text ) && overload::Method( $text, '""' ) ) )
4076 {
4077 warn( "I was provided a reference '$text' as a result from calling this code reference to get the replacement text for tag \"", $e->tag, "\", but I do not know what to do with it.\n" );
4078 return(1);
4079 }
4080 $text = "$text";
4081 $text =~ s/</\&lt;/gs;
4082 $text =~ s/>/\&gt;/gs;
4083 $text =~ s,\n,<br />\n,gs;
4084 if( $self->isa( 'HTML::Object::DOM::Comment' ) ||
4085 $self->isa( 'HTML::Object::DOM::Text' ) )
4086 {
4087 $self->value( $text );
4088 }
4089 else
4090 {
4091 my $new = $self->new_text( value => $text, parent => $self );
4092 # If this is an empty tag, such as <input /> or <img />, the text cannot be added to it.
4093 # jQuery actually accepts the text and attach it to the element as a child, but the web browser does not show it, because it is an empty element.
4094 # Since this is not a web browser interface, we need to silently ignore it, so it does not end up in the DOM and turn an empty tag into a tag with children and a closing tag, which would be an heresy.
4095 if( !$e->is_empty )
4096 {
4097 $e->children->set( $new );
4098 }
4099 }
4100 }
4101 else
4102 {
4103 my $new = $self->new_text( value => $this, parent => $e );
4104 # See comment just above
4105 if( !$e->is_empty )
4106 {
4107 $e->children->set( $new );
4108 }
4109 }
4110 };
4111  
4112 if( $self->isa_collection )
4113 {
4114 $self->children->for(sub
4115 {
4116 my( $i, $e ) = @_;
4117 $process->( $e, $i );
4118 $e->reset(1);
4119 # Return true at the end to satisfy Module::Generic::Array->for
4120 return(1);
4121 });
4122 }
4123 else
4124 {
4125 $process->( $self, 0 );
4126 $self->reset(1);
4127 }
4128 }
4129 # Accessor
4130 else
4131 {
4132 return( $self->as_text( unescape => 1 ) );
4133 }
4134 }
4135  
4136 # Takes a class name; or
4137 # class name and state (true or false); or
4138 # array of class names; or
4139 # array of class names and a state; or
4140 # a code reference called with the index position of the current class and its name. Returns a space separated list of classes or an array
4141 # <https://api.jquery.com/toggleClass/>
4142 sub toggleClass
4143 {
4144 my $self = shift( @_ );
4145 my $this;
4146 $this = shift( @_ ) if( @_ );
4147 my $state;
4148 $state = scalar( @_ ) ? shift( @_ ) : 1;
4149 my $a = $self->new_array;
4150 my $has_code = 0;
4151 if( defined( $this ) )
4152 {
4153 if( $self->_is_array( $this ) )
4154 {
4155 $a = $self->new_array( $this );
4156 }
4157 elsif( ref( $this ) CORE::eq 'CODE' )
4158 {
4159 # ok
4160 $has_code++;
4161 }
4162 elsif( ref( $this ) && overload::Overloaded( $this ) && overload::Method( $this, '""' ) )
4163 {
4164 $a = $self->new_array( [split( /[[:blank:]\h]+/, "$this" )] );
4165 }
4166 else
4167 {
4168 return( $self->error( "I was expecting an array reference of classes, or class string or a code reference, but instead I got '$this', and I do not know what to do with it." ) );
4169 }
4170 # Make sure the classes we are provided are unique
4171 $a->unique(1);
4172 }
4173  
4174 my $process;
4175 $process = sub
4176 {
4177 my( $i, $e ) = @_;
4178 my $ref = $e->internal->{class};
4179 $ref //= {};
4180 $ref->{toggle_status} //= 0;
4181 my $classes;
4182 if( $e->attributes->exists( 'class' ) )
4183 {
4184 $classes = $self->new_array( [split( /[[:blank:]\h]+/, $e->attributes->get( 'class' ) )] );
4185 $ref->{original_classes} //= $classes;
4186 }
4187 # No class on this element yet
4188  
4189 if( $has_code )
4190 {
4191 local $_ = $e;
4192 my $res = $this->( $i, $classes, $ref->{toggle_status} );
4193 if( $self->_is_array( $res ) )
4194 {
4195 $a = $self->new_array( $res );
4196 }
4197 elsif( !ref( $res ) || ( overload::Overloaded( $res ) && overload::Method( $res, '""' ) ) )
4198 {
4199 $a = $self->new_array( [ split( /[[:blank:]\h]+/, "$res" ) ] );
4200 }
4201 else
4202 {
4203 warn( "Code reference for class of element with tag \"", $e->tag, "\" returned '$this', but I do not know what to do with it.\n" );
4204 return( 1 );
4205 }
4206 $a->unique(1);
4207 }
4208  
4209 # No class set yet on this element
4210 if( !defined( $classes ) )
4211 {
4212 # and we have no class either, so we skip to the next element. Nothing to do here
4213 if( !$a->length )
4214 {
4215 return(1);
4216 }
4217 # we activate our classes
4218 else
4219 {
4220 $ref->{toggle_status} = 1;
4221 $e->attributes->set( class => $a->join( ' ' ) );
4222 $e->reset(1);
4223 }
4224 }
4225 else
4226 {
4227 # we found existing class, and we toggled without specifying any
4228 # which mean we switch them all on/off
4229 if( !$a->length )
4230 {
4231 $e->attributes->set( class => ( $ref->{toggle_status} ? $ref->{original_classes} : '' ) );
4232 }
4233 # Specific were provided. We toggle them on/off
4234 else
4235 {
4236 if( $ref->{toggle_status} )
4237 {
4238 $classes->remove( $a );
4239 }
4240 else
4241 {
4242 $classes->push( $a->list )->unique;
4243 }
4244 $e->attributes->set( class => $classes->join( ' ' ) );
4245 $e->reset(1);
4246 $ref->{toggle_status} = !$ref->{toggle_status};
4247 }
4248 }
4249 };
4250  
4251 if( $self->isa_collection )
4252 {
4253 $self->children->for( $process );
4254 }
4255 else
4256 {
4257 $process->( 0, $self );
4258 }
4259 }
4260  
4261 sub to_number { return( HTML::Object::DOM::Number->new( shift->getValue ) ); }
4262  
4263 sub toString { return( shift->as_xml( @_ ) ); }
4264  
4265 sub uniqueSort
4266 {
4267 my $self = shift( @_ );
4268 my $collection = $self->new_collection;
4269 if( $self->isa_collection )
4270 {
4271 my $elems = xQuery->uniqueSort( $self->children ) ||
4272 return( $self->pass_error( xQuery->error ) );
4273 $collection->children->push( $elems->list );
4274 }
4275 else
4276 {
4277 $collection->children->push( $self );
4278 }
4279 return( $collection );
4280 }
4281  
4282 sub wrap
4283 {
4284 my $self = shift( @_ );
4285 my @args = @_;
4286 my( $this, $more ) = @args;
4287 return( $self->error( "Nothing was provided to wrap elements." ) ) if( !$this );
4288 my( $wrapper, $elems, $is_code );
4289 # "When you pass a collection object containing more than one element, or a selector matching more than one element, the first element will be used."
4290 if( $self->_is_a( $this => 'HTML::Object::Collection' ) )
4291 {
4292 return( $self->error( "Collection provided as wrapper is actually empty!" ) ) if( $this->children->is_empty );
4293 $wrapper = $this->children->first;
4294 return( $self->error( "The first element of the collection provided did not yield an element object." ) ) if( !$self->_is_a( $wrapper => 'HTML::Object::DOM::Element' ) );
4295 }
4296 elsif( $self->_is_a( $this => 'HTML::Object::DOM::Element' ) )
4297 {
4298 $wrapper = $this;
4299 }
4300 elsif( $self->_is_code( $this ) )
4301 {
4302 $is_code = 1;
4303 $wrapper = $this;
4304 }
4305 # selector, html to parse
4306 else
4307 {
4308 my $tmp = xq( @args ) || return( $self->pass_error );
4309 return( $self->error( "Selector or HTML provided as wrapper did not yield any wrapping element." ) ) if( $tmp->children->is_empty );
4310 $wrapper = $tmp->children->first ||
4311 return( $self->error( "Collection returned from selector or HTML provided is empty." ) );
4312 return( $self->error( "Collection returned from selector or HTML provided did not yield an element object." ) ) if( !$self->_is_a( $wrapper => 'HTML::Object::DOM::Element' ) );
4313 }
4314  
4315 if( $self->isa_collection )
4316 {
4317 $elems = $self->children;
4318 }
4319 else
4320 {
4321 $elems = $self->new_array( $self );
4322 }
4323  
4324 my $find_nested;
4325 $find_nested = sub
4326 {
4327 my( $el, $kids ) = @_;
4328 my $n = $kids->length;
4329 if( !$n )
4330 {
4331 return( $el );
4332 }
4333 elsif( $n == 1 )
4334 {
4335 return( $find_nested->( $kids->[0] => $kids->[0]->children ) );
4336 }
4337 else
4338 {
4339 return( '' );
4340 }
4341 };
4342  
4343 local $@;
4344 for( my $i = 0; $i < scalar( @$elems ); $i++ )
4345 {
4346 my $e = $elems->[$i];
4347 my $parent = $e->parent;
4348 my $pos = $parent->children->pos( $e );
4349 return( $self->error( "Unable to find element No $i position in its parent." ) ) if( !defined( $pos ) );
4350 my $wrap;
4351 if( $is_code )
4352 {
4353 # try-catch
4354 my $rv = eval
4355 {
4356 local $_ = $e;
4357 $wrapper->( $i );
4358 };
4359 if( $@ )
4360 {
4361 return( $self->error( "An error occurred executing the wrapper callback code reference for element at offset $i: $@" ) );
4362 }
4363 my $thingy;
4364 if( $self->_is_a( $rv => 'HTML::Object::Collection' ) )
4365 {
4366 return( $self->error( "Collection provided as wrapper is actually empty!" ) ) if( $rv->children->is_empty );
4367 $thingy = $rv->children->first;
4368 return( $self->error( "The first element of the collection provided did not yield an element object." ) ) if( !$self->_is_a( $thingy => 'HTML::Object::DOM::Element' ) );
4369 }
4370 elsif( $self->_is_a( $rv => 'HTML::Object::DOM::Element' ) )
4371 {
4372 $thingy = $rv;
4373 }
4374 # selector, html to parse
4375 else
4376 {
4377 my $tmp = xq( $rv, ( defined( $more ) ? $more : () ) ) || return( $self->pass_error );
4378 return( $self->error( "Selector or HTML returned from callback as wrapper did not yield any wrapping element." ) ) if( $tmp->children->is_empty );
4379 $thingy = $tmp->children->first ||
4380 return( $self->error( "Collection returned from selector or HTML provided is empty." ) );
4381 return( $self->error( "Collection returned from selector or HTML provided did not yield an element object." ) ) if( !$self->_is_a( $thingy => 'HTML::Object::DOM::Element' ) );
4382 }
4383 $wrap = $thingy->clone;
4384 }
4385 else
4386 {
4387 $wrap = $wrapper->clone;
4388 }
4389 my $nested = $find_nested->( $wrap => $wrap->children );
4390 # $e->detach;
4391 $wrap->parent( $parent );
4392 $parent->children->splice( $pos, 1, $wrap );
4393 $nested->children->set( $e );
4394 $e->parent( $nested );
4395 }
4396 return( $self );
4397 }
4398  
4399 sub xp
4400 {
4401 my $self = shift( @_ );
4402 unless( $XP )
4403 {
4404 $XP = HTML::Object::XPath->new;
4405 }
4406 # $XP->debug( $self->debug );
4407 return( $XP );
4408 }
4409  
4410 # Ref: <https://api.jquery.com/Types/#jQuery>
4411 # xq( '#myId', $document )
4412 # xq( '<div />', { id => 'Pouec', class => 'Hello' } );
4413 # xq( '<html><head><title>Hello world</title></head><body>Hello!</body></html>' );
4414 # xq();
4415 sub xq
4416 {
4417 my( @args ) = @_;
4418 # Check if this might be all some HTML::Object::DOM::Element objects passed to form a collection
4419 my $is_all_objects = 1;
4420 no warnings 'once';
4421 my $opts =
4422 {
4423 xq_debug => $HTML::Object::xQuery::DEBUG,
4424 };
4425 if( scalar( @args ) > 1 &&
4426 defined( $args[-1] ) &&
4427 ref( $args[-1] ) eq 'HASH' &&
4428 CORE::exists( $args[-1]->{xq_debug} ) )
4429 {
4430 $opts = CORE::pop( @args );
4431 }
4432 # A dummy accessor
4433 my $self = HTML::Object::DOM::Element->new( debug => $opts->{xq_debug} );
4434 # We check if xq was not called with a bunch of HTML::Object::DOM::Element objects, such as:
4435 # $(@elements) or maybe xq(@elements), which would return a new collection.
4436 for( my $i = 0; $i < scalar( @args ); $i++ )
4437 {
4438 unless( $self->_is_a( $args[$i] => 'HTML::Object::DOM::Element' ) )
4439 {
4440 $is_all_objects = 0;
4441 last;
4442 }
4443 }
4444 # Shortcut
4445 if( $is_all_objects )
4446 {
4447 my $collection = $self->new_collection( debug => $opts->{xq_debug} );
4448 $collection->children->set( @args );
4449 return( $collection );
4450 }
4451 my( $this, $more ) = @args;
4452 # e.g. $('<div />', { id => 'pouec', class => 'hello' });
4453 if( $this =~ /^$LOOK_LIKE_HTML/ )
4454 {
4455 my $p = HTML::Object::DOM->new;
4456 $this = "$this";
4457 # We trim the string, so that leading and trailing space do not get counted
4458 $this =~ s/^[[:blank:]\h\v]+|[[:blank:]\h\v]+$//gs;
4459 my $doc = $p->parse_data( $this ) || do
4460 {
4461 $! = $p->error;
4462 return;
4463 };
4464 # $doc is a HTML::Object::DOM::Document, which is not suitable, so we change it to a
4465 # collection object
4466 my $collection = $doc->new_collection;
4467 $collection->children( $doc->children );
4468 if( $doc->children->length == 1 )
4469 {
4470 my $e = $doc->children->first;
4471 # I do not use Module::Generic::_is_hash on purpose because I do not want to catch objects inadvertently
4472 # We found attributes, so we set them up now
4473 if( ref( $more ) CORE::eq 'HASH' )
4474 {
4475 my $debug = CORE::delete( $more->{_debug} ) if( CORE::exists( $more->{_debug} ) );
4476 $e->attributes->merge( $more );
4477 $e->debug( $debug );
4478 $collection->debug( $debug );
4479 }
4480 # We correct a situation where the user called for example $('<div />', { class => 'hello', id => 'pouec' });
4481 # And this would lead the parser to flag it to be empty, respecting the user decision,
4482 # but in this case, this is merely a short-hand notation to create a tag, and is not a
4483 # reflexion that this tag should indeed be treated as empty when it is not by standard
4484 # hus, we correct it here.
4485 if( $e->children->length == 0 && $e->is_empty )
4486 {
4487 my $def = $p->get_definition( $e->tag );
4488 $e->is_empty(0) if( !$def->{is_empty} );
4489 $e->close;
4490 }
4491 }
4492 return( $collection );
4493 }
4494 # Hmmm, I wanted to support $.parseXML and consequently allow $($xmlDoc), but our interface is really just tailored for HTML::Object::Element and not for XML::libXML, so all of the HTML::Object::XQuery methods would not work.
4495 # elsif( $self->_is_a( $this => 'XML::LibXML::Node' ) )
4496 # {
4497 # my $collection = $self->new_collection;
4498 # my @childnodes = $this->childNodes;
4499 # $collection->children->push( @childNodes );
4500 # return( $collection );
4501 # }
4502 elsif( ( !ref( $this ) || ( overload::Overloaded( $this ) && overload::Method( $this, '""' ) ) ) && CORE::index( "$this", "\n" ) == -1 )
4503 {
4504 # e.g. $('div')
4505 if( !defined( $more ) )
4506 {
4507 # e.g. $('body')
4508 if( defined( $HTML::Object::DOM::GLOBAL_DOM ) )
4509 {
4510 my $collection = $HTML::Object::DOM::GLOBAL_DOM->find( $this ) || return;
4511 $collection->debug( $self->debug );
4512 return( $collection );
4513 }
4514 else
4515 {
4516 warn( "No context was specified for '$this'. You need to provide some context to the selector by supplying an HTML::Object::DOM::Element object." ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
4517 return( HTML::Object::DOM->error( "You need to provide some context to the selector by supplying an HTML::Object::DOM::Element object." ) );
4518 }
4519 }
4520 # e.g., with context: $('div', $element);
4521 elsif( !ref( $more ) || ( ref( $more ) && !$more->isa( 'HTML::Object::DOM::Element' ) ) )
4522 {
4523 return( HTML::Object::DOM->error( "Context provided selector must be an element object. Got '", overload::StrVal( $more ), "'" ) );
4524 }
4525 my $collection = $more->find( $this ) || return( HTML::Object::DOM->pass_error( $more->error ) );
4526 $collection->debug( $more->debug );
4527 return( $collection );
4528 }
4529 else
4530 {
4531 return( HTML::Object::DOM->error( "I do not know what to do with '$this'." ) );
4532 }
4533 }
4534  
4535 sub _append_prepend
4536 {
4537 my $self = shift( @_ );
4538 my $this = shift( @_ ) || return( $self->error( "Nothing was provided to append or prepend." ) );
4539 my $opts = $self->_get_args_as_hash( @_ );
4540 if( !exists( $opts->{action} ) )
4541 {
4542 my @caller_info = caller(1);
4543 my $caller = [split( /::/, $caller_info[3])]->[-1];
4544 return( $self->error( "No action argument was provided and I am unable to guess it." ) ) if( $caller !~ /^(append|prepend)$/ );
4545 $opts->{action} = $caller;
4546 }
4547 return( $self->error( "Invalid value for argument \"action\": '$opts->{action}'" ) ) if( $opts->{action} !~ /^(append|prepend)$/ );
4548 my $a;
4549 if( !ref( $this ) )
4550 {
4551 my $p = $self->new_parser;
4552 $this = $p->parse_data( $this ) || return( $self->pass_error( $p->error ) );
4553 $a = $self->new_array( [ $this ] );
4554 }
4555 elsif( $self->_is_array( $this ) )
4556 {
4557 # Make sure this is a Module::Generic::Array object
4558 $a = $self->new_array( $this );
4559 }
4560 elsif( $self->_is_object( $this ) )
4561 {
4562 return( $self->error( "Object provided '$this' (", overload::StrVal( $this ), ") is not an HTML::Object::DOM::Element object." ) ) if( !$this->isa( 'HTML::Object::DOM::Element' ) );
4563 $a = $self->new_array( [ $this ] );
4564 }
4565 elsif( ref( $this ) ne 'CODE' )
4566 {
4567 return( $self->error( "I do not know what to do with '$this'. I was expecing an html string, or an HTML::Object::DOM::Element or an array of element objects or a collection object (HTML::Object::Collection) or a code reference." ) );
4568 }
4569  
4570 if( $self->isa_collection )
4571 {
4572 my $failed = 0;
4573 # Going through each object in the collection
4574 $self->children->for(sub
4575 {
4576 my( $i, $e ) = @_;
4577 $e->reset(1);
4578 # will silently fail just like jQuery does
4579 my $parent = $e->parent;
4580 my $pos = $parent ? $parent->children->pos( $e ) : $i;
4581 if( ref( $this ) CORE::eq 'CODE' )
4582 {
4583 local $_ = $e;
4584 my $res = $this->( $pos, $e->as_string );
4585 if( !defined( $res ) )
4586 {
4587 $failed++;
4588 $self->error( "An error occurred while executing code reference to $opts->{action} html element(s). Code reference returned undef." );
4589 return(0);
4590 }
4591 if( $self->_is_object( $res ) && $res->isa( 'HTML::Object::DOM::Element' ) )
4592 {
4593 $a = $self->new_array( [ $res ] );
4594 }
4595 elsif( overload::Overloaded( $res ) && overload::Method( $res, '""' ) )
4596 {
4597 my $elem = $self->new_parser( "$res" );
4598 if( !defined( $elem ) )
4599 {
4600 $failed++;
4601 return(0);
4602 }
4603 $a = $self->new_array( [ $elem ] );
4604 }
4605 else
4606 {
4607 $failed++;
4608 $self->error( "Value returned from code reference to be used in $opts->{action}\(\) is neither a string nor a HTML::Object::DOM::Element, so I do not know what to do with it." );
4609 return(0);
4610 }
4611 }
4612 $a->foreach(sub
4613 {
4614 my $elem = $_->detach->clone;
4615 $elem->parent( $e );
4616 if( $opts->{action} CORE::eq 'append' )
4617 {
4618 $e->children->push( $elem );
4619 }
4620 elsif( $opts->{action} CORE::eq 'prepend' )
4621 {
4622 $e->children->unshift( $elem );
4623 }
4624 });
4625 });
4626 return if( $failed );
4627 }
4628 else
4629 {
4630 $self->reset(1);
4631 # will silently fail just like jQuery does
4632 my $parent = $self->parent;
4633 my $pos = $parent ? $parent->children->pos( $self ) : 0;
4634 if( ref( $this ) CORE::eq 'CODE' )
4635 {
4636 local $_ = $self;
4637 my $res = $this->( $pos, $self->as_string );
4638 return( $self->error( "An error occurred while executing code reference to $opts->{action} html element(s). Code reference returned undef." ) ) if( !defined( $res ) );
4639 if( $self->_is_object( $res ) && $res->isa( 'HTML::Object::DOM::Element' ) )
4640 {
4641 $a = $self->new_array( [ $res ] );
4642 }
4643 elsif( overload::Overloaded( $res ) && overload::Method( $res, '""' ) )
4644 {
4645 my $elem = $self->new_parser( "$res" );
4646 return if( !defined( $elem ) );
4647 $a = $self->new_array( [ $elem ] );
4648 }
4649 else
4650 {
4651 return( $self->error( "Value returned from code reference to be used in $opts->{action}\(\) is neither a string nor a HTML::Object::DOM::Element, so I do not know what to do with it." ) );
4652 }
4653 }
4654 $a->foreach(sub
4655 {
4656 $_->detach();
4657 $_->parent( $self );
4658 if( $opts->{action} CORE::eq 'append' )
4659 {
4660 $self->children->push( $_ );
4661 }
4662 elsif( $opts->{action} CORE::eq 'prepend' )
4663 {
4664 $self->children->unshift( $_ );
4665 }
4666 });
4667 }
4668 return( $self );
4669 }
4670  
4671 # Takes html string; or
4672 # selector; or
4673 # element object; or
4674 # array of objects; or
4675 # collection
4676 # "If there is more than one target element, however, cloned copies of the inserted element will be created for each target except the last, and that new set (the original element plus clones) is returned."
4677 sub _append_prepend_to
4678 {
4679 my $self = shift( @_ );
4680 my $this = shift( @_ ) || return( $self->error( "No target was provided to insert element." ) );
4681 # For example: $sel->appendTo( 'body', $doc );
4682 my $context = shift( @_ ) if( $self->_is_a( $_[0] => 'HTML::Object::DOM::Element' ) );
4683 my $opts = $self->_get_args_as_hash( @_ );
4684 if( !exists( $opts->{action} ) )
4685 {
4686 my @caller_info = caller(1);
4687 my $caller = [split( /::/, $caller_info[3])]->[-1];
4688 return( $self->error( "No action argument was provided and I am unable to guess it." ) ) if( $caller !~ /^(appendTo|prependTo|append_to|prepend_to)$/ );
4689 $opts->{action} = ( $caller =~ /^(append|prepend)(?:To|_to)$/ )[0];
4690 }
4691 return( $self->error( "Invalid value for argument \"action\": '$opts->{action}'" ) ) if( $opts->{action} !~ /^(append|prepend)$/ );
4692 my( $src, $dst );
4693 # A collection to be returned if there is more than 1 target
4694 my $collection = $self->new_collection;
4695 if( !ref( $this ) )
4696 {
4697 if( $self->_is_html( $this ) )
4698 {
4699 my $p = $self->new_parser;
4700 $this = $p->parse_data( $this ) || return( $self->pass_error( $p->error ) );
4701 $dst = $self->new_array( [ $this ] );
4702 }
4703 # otherwise this has to be a selector
4704 # TODO: Need to correct this and adjust the object used as a base for the find
4705 # since $self could very well be a dynamically created dom object
4706 else
4707 {
4708 if( !defined( $context ) &&
4709 defined( $HTML::Object::DOM::GLOBAL_DOM ) )
4710 {
4711 $context = $HTML::Object::DOM::GLOBAL_DOM;
4712 }
4713 elsif( !defined( $context ) &&
4714 $self->isa_collection &&
4715 !$self->children->is_empty )
4716 {
4717 $context = $self->children->first->getRootNode;
4718 }
4719 $this = defined( $context ) ? $context->find( $this ) : $self->find( $this );
4720 return( $self->pass_error ) unless( $this );
4721 # $dst = $self->new_array( [ $this ] );
4722 $dst = $this->children;
4723 }
4724 }
4725 elsif( $self->_is_array( $this ) )
4726 {
4727 # Make sure this is a Module::Generic::Array object
4728 $dst = $self->new_array( $this );
4729 }
4730 elsif( $self->_is_object( $this ) )
4731 {
4732 return( $self->error( "Object provided '$this' (", overload::StrVal( $this ), ") is not an HTML::Object::DOM::Element object." ) ) if( !$this->isa( 'HTML::Object::DOM::Element' ) );
4733 $dst = $self->new_array( [ $this ] );
4734 }
4735 else
4736 {
4737 return( $self->error( "I do not know what to do with \"$this\". I was expecting a selector, html data, an element object or an array." ) );
4738 }
4739  
4740 # If the content to be inserted is a collection, we loop through it, duplicate each element and insert them
4741 if( $self->isa_collection )
4742 {
4743 $src = $self->children;
4744 }
4745 else
4746 {
4747 $src = $self->new_array( $self );
4748 }
4749  
4750 # If the target is just one element, we do not duplicate them, but simply move them
4751 if( $dst->length == 1 )
4752 {
4753 my $elem = $dst->first;
4754 my $parent = $elem->parent;
4755 return( 1 ) if( !$parent );
4756 $elem->reset(1);
4757 my $pos = $parent->children->pos( $elem );
4758 return( $self->error( "Found a parent for tag \"", $elem->tag, "\", but somehow I could not find its position among its children elements." ) ) if( !defined( $pos ) );
4759 $src->foreach(sub
4760 {
4761 my $e = shift( @_ );
4762 # Making sure the content element is detached from its original parent
4763 $e->detach;
4764 $e->parent( $elem );
4765 $e->reset(1);
4766 if( $opts->{action} CORE::eq 'prepend' )
4767 {
4768 $elem->children->unshift( $e );
4769 }
4770 elsif( $opts->{action} CORE::eq 'append' )
4771 {
4772 $elem->children->push( $e );
4773 }
4774 $collection->children->push( $e );
4775 });
4776 }
4777 # However, if the target contain multiple element, we clone the content element
4778 else
4779 {
4780 $dst->foreach(sub
4781 {
4782 my $elem = $_;
4783 my $parent = $elem->parent;
4784 return(1) if( !$parent );
4785 $elem->reset(1);
4786 my $pos = $parent->children->pos( $elem );
4787 warn( "Found a parent for tag \"", $elem->tag, "\", but somehow I could not find its position among its children elements.\n" ) if( !defined( $pos ) );
4788 return(1) if( !defined( $pos ) );
4789 $src->foreach(sub
4790 {
4791 my $e = shift( @_ );
4792 # Making sure the content element is detached from its original parent
4793 my $clone = $e->detach->clone;
4794 $clone->parent( $elem );
4795 $clone->reset(1);
4796 if( $opts->{action} CORE::eq 'prepend' )
4797 {
4798 $elem->children->unshift( $clone );
4799 }
4800 elsif( $opts->{action} CORE::eq 'append' )
4801 {
4802 $elem->children->push( $clone );
4803 }
4804 $collection->children->push( $clone );
4805 });
4806 });
4807 }
4808 return( $collection );
4809 }
4810  
4811 # Takes html string (start with <tag...), text object (HTML::Object::DOM::Text), array or element object
4812 # or alternatively a code reference that returns the above
4813 sub _before_after
4814 {
4815 my $self = shift( @_ );
4816 my $this = shift( @_ ) || return( $self->error( "Nothing was provided to insert before or after." ) );
4817 my $opts = $self->_get_args_as_hash( @_ );
4818 if( !exists( $opts->{action} ) )
4819 {
4820 my @caller_info = caller(1);
4821 my $caller = [split( /::/, $caller_info[3])]->[-1];
4822 return( $self->error( "No action argument was provided and I am unable to guess it." ) ) if( $caller !~ /^(before|after)$/ );
4823 $opts->{action} = $caller;
4824 }
4825 return( $self->error( "Invalid value for argument \"action\": '$opts->{action}'" ) ) if( $opts->{action} !~ /^(before|after)$/ );
4826 my $a;
4827 if( !ref( $this ) )
4828 {
4829 my $p = $self->new_parser;
4830 $this = $p->parse_data( $this ) || return( $self->pass_error( $p->error ) );
4831 # $a = $self->new_array( [ $this ] );
4832 # $this is a HTML::Document; we take its children
4833 $a = $this->children;
4834 }
4835 elsif( $self->_is_array( $this ) )
4836 {
4837 # Make sure this is a Module::Generic::Array object
4838 $a = $self->new_array( $this );
4839 }
4840 elsif( $self->_is_object( $this ) )
4841 {
4842 return( $self->error( "Object provided '$this' (", overload::StrVal( $this ), ") is not an HTML::Object::DOM::Element object." ) ) if( !$this->isa( 'HTML::Object::DOM::Element' ) );
4843 $a = $self->new_array( [ $this ] );
4844 }
4845 elsif( ref( $this ) ne 'CODE' )
4846 {
4847 return( $self->error( "I do not know what to do with '$this'. I was expecing an html string, or an HTML::Object::DOM::Element or an array of element objects or a collection object (HTML::Object::Collection) or a code reference." ) );
4848 }
4849  
4850 if( $self->isa_collection )
4851 {
4852 my $failed = 0;
4853 # Going through each object in the collection
4854 $self->children->for(sub
4855 {
4856 my( $i, $e ) = @_;
4857 $e->reset(1);
4858 # will silently fail just like jQuery does
4859 my $parent = $e->parent;
4860 return( 1 ) if( !$parent );
4861 my $pos;
4862 if( $opts->{action} CORE::eq 'before' )
4863 {
4864 $pos = $parent->children->pos( $e );
4865 }
4866 elsif( $opts->{action} CORE::eq 'after' )
4867 {
4868 # $pos = $parent->children->pos( $e->close_tag ? $e->close_tag : $e );
4869 $pos = $parent->children->pos( $e );
4870 }
4871 if( !defined( $pos ) )
4872 {
4873 $failed++;
4874 $self->error( "Element with tag \"", $e->tag, "\" has a parent, but I could not find it among its children elements." );
4875 return(0);
4876 }
4877 if( ref( $this ) CORE::eq 'CODE' )
4878 {
4879 local $_ = $e;
4880 my $res = $this->( $pos, $e->as_string );
4881 if( !defined( $res ) )
4882 {
4883 $failed++;
4884 $self->error( "An error occurred while executing code reference to $opts->{action} html element(s). Code reference returned undef." );
4885 return(0);
4886 }
4887 if( $self->_is_object( $res ) && $res->isa( 'HTML::Object::DOM::Element' ) )
4888 {
4889 $a = $self->new_array( [ $res ] );
4890 }
4891 elsif( overload::Overloaded( $res ) && overload::Method( $res, '""' ) )
4892 {
4893 my $elem = $self->new_parser( "$res" );
4894 if( !defined( $elem ) )
4895 {
4896 $failed++;
4897 return(0);
4898 }
4899 $a = $self->new_array( [ $elem ] );
4900 }
4901 else
4902 {
4903 $failed++;
4904 $self->error( "Value returned from code reference to be used in $opts->{action}\(\) is neither a string nor a HTML::Object::DOM::Element, so I do not know what to do with it." );
4905 return(0);
4906 }
4907 }
4908 $a->foreach(sub
4909 {
4910 my $elem = $_->clone;
4911 $elem->parent( $e );
4912 if( $opts->{action} CORE::eq 'before' )
4913 {
4914 $parent->children->splice( $pos, 0, $_ );
4915 }
4916 elsif( $opts->{action} CORE::eq 'after' )
4917 {
4918 $parent->children->splice( $pos + 1, 0, $_ );
4919 }
4920 $pos++;
4921 });
4922 });
4923 return( $self->pass_error ) if( $failed );
4924 }
4925 else
4926 {
4927 # will silently fail just like jQuery does
4928 my $parent = $self->parent;
4929 return(1) if( !$parent );
4930 my $pos = $parent->children->pos( $self );
4931 return( $self->error( "Element with tag \"", $self->tag, "\" has a parent, but I could not find it among its children elements." ) ) if( !defined( $pos ) );
4932 if( ref( $this ) CORE::eq 'CODE' )
4933 {
4934 local $_ = $self;
4935 my $res = $this->( $pos, $self->as_string );
4936 return( $self->error( "An error occurred while executing code reference to $opts->{action} html element(s). Code reference returned undef." ) ) if( !defined( $res ) );
4937 if( $self->_is_object( $res ) && $res->isa( 'HTML::Object::DOM::Element' ) )
4938 {
4939 $a = $self->new_array( [ $res ] );
4940 }
4941 elsif( overload::Overloaded( $res ) && overload::Method( $res, '""' ) )
4942 {
4943 my $elem = $self->new_parser( "$res" );
4944 return if( !defined( $elem ) );
4945 $a = $self->new_array( [ $elem ] );
4946 }
4947 else
4948 {
4949 return( $self->error( "Value returned from code reference to be used in $opts->{action}\(\) is neither a string nor a HTML::Object::DOM::Element, so I do not know what to do with it." ) );
4950 }
4951 }
4952 $a->foreach(sub
4953 {
4954 $_->detach();
4955 $_->parent( $self );
4956 $_->reset(1);
4957 if( $opts->{action} CORE::eq 'before' )
4958 {
4959 $parent->children->splice( $pos, 0, $_ );
4960 }
4961 elsif( $opts->{action} CORE::eq 'after' )
4962 {
4963 $parent->children->splice( $pos + 1, 0, $_ );
4964 }
4965 });
4966 }
4967 return( $self );
4968 }
4969  
4970 sub _same_as
4971 {
4972 my $self = shift( @_ );
4973 my $this = shift( @_ );
4974 return(0) if( !defined( $this ) || !$self->_is_object( $this ) || !$this->isa( 'HTML::Object::DOM::Element' ) );
4975 if( $this->isa_collection )
4976 {
4977 # We are not a collection, but the other is
4978 if( !$self->isa_collection )
4979 {
4980 return(0);
4981 }
4982 # https://css-tricks.com/snippets/jquery/compare-jquery-objects/
4983 elsif( $self->length == $this->length &&
4984 $self->length == $self->filter( $this )->length )
4985 {
4986 return(1);
4987 }
4988 else
4989 {
4990 return(0);
4991 }
4992 }
4993 else
4994 {
4995 return(0) if( $self->tag CORE::ne $this->tag );
4996 return( $self->eid CORE::eq $this->eid ? 1: 0 );
4997 }
4998 }
4999  
5000 # If argument is provided, pass a CSS::Object::Builder::Rule object
5001 # If no argument is provided, get a CSS::Object::Builder::Rule of the inline css, if any at all.
5002 # Returns undef if no css attribute is set yet.
5003 sub _css_object
5004 {
5005 my $self = shift( @_ );
5006 if( @_ )
5007 {
5008 my $rule = shift( @_ );
5009 my $css = $rule->css;
5010 my $style = $rule->as_string;
5011 $self->css_cache_store( $style, $css );
5012 $self->attributes->set( css => $style );
5013 return( $rule );
5014 }
5015 else
5016 {
5017 my $style = $self->attributes->get( 'css' );
5018 return if( !defined( $style ) );
5019 my $css = CSS::Object->new( format => 'CSS::Object::Format::Inline', debug => $self->debug );
5020 my $cached = $self->css_cache_check( $style );
5021 if( $cached )
5022 {
5023 $css = $cached;
5024 }
5025 else
5026 {
5027 ## 'inline' here is just a fake selector to serve as a container rule for the inline properties,
5028 ## because CSS::Object requires properties to be within a rule
5029 $css->read_string( 'inline {' . $style . ' }' ) ||
5030 return( $self->error( "Unable to parse existing style for tag name \"", $self->prop( 'tagName' ), "\":", $css->error ) );
5031 }
5032 my $main = $css->rules->first;
5033 my $rule = defined( $main ) ? $css->builder->select( $main ) : $css->builder->select( 'inline' );
5034 return( $rule );
5035 }
5036 }
5037  
5038 sub _css_builder
5039 {
5040 my $self = shift( @_ );
5041 my $css = CSS::Object->new( format => 'CSS::Object::Format::Inline', debug => $self->debug );
5042 return( $css->builder->select( 'inline' ) );
5043 }
5044  
5045 # Private method : BFS (Breadth-First Search) on the sub-tree of $self, returns an array
5046 # of all the elements for which $test->($elem) is true. Ignores the nodes text/space/comment.
5047 sub _fast_find_by
5048 {
5049 my( $self, $test ) = @_;
5050 my $result = $self->new_array;
5051 # Racine(s) à parcourir
5052 my @roots;
5053 if( $self->isa_collection )
5054 {
5055 @roots = $self->children->list;
5056 }
5057 else
5058 {
5059 @roots = ( $self );
5060 }
5061 my @queue = @roots;
5062 while( @queue )
5063 {
5064 my $node = shift( @queue );
5065 # We only test on the true elements, no on Text, Space, or Comment
5066 if( $node->isa( 'HTML::Object::DOM::Element' ) &&
5067 $node->{tag} &&
5068 substr( "$node->{tag}", 0, 1 ) ne '_' )
5069 {
5070 $result->push( $node ) if( $test->( $node ) );
5071 }
5072 # Crawl down in te children if the method exists.
5073 if( $node->can( 'children' ) && $node->children->length )
5074 {
5075 push( @queue, $node->children->list );
5076 }
5077 }
5078 return( $result );
5079 }
5080  
5081 # Takes selector, html, element or array
5082 # xq( '<p>Test</p>' )->insertBefore( xq( '.inner', $doc ) );
5083 # $elem->insertBefore( '.inner' );
5084 sub _insert_before_after
5085 {
5086 my $self = shift( @_ );
5087 my $this = shift( @_ ) || return( $self->error( "No target was provided to insert element." ) );
5088 my $opts = $self->_get_args_as_hash( @_ );
5089 if( !exists( $opts->{action} ) )
5090 {
5091 my @caller_info = caller(1);
5092 my $caller = [split( /::/, $caller_info[3])]->[-1];
5093 return( $self->error( "No action argument was provided and I am unable to guess it." ) ) if( $caller !~ /^(?:insert|insert_)(?:Before|After)$/i );
5094 $opts->{action} = lc( ( $caller =~ /^(?:insert|insert_)(?:Before|After)$/i )[0] );
5095 }
5096 return( $self->error( "Invalid value for argument \"action\": '$opts->{action}'" ) ) if( $opts->{action} !~ /^(?:before|after)$/ );
5097 my $a;
5098 if( !ref( $this ) )
5099 {
5100 if( $self->_is_html( $this ) )
5101 {
5102 my $p = $self->new_parser;
5103 $this = $p->parse_data( $this ) || return( $self->pass_error( $p->error ) );
5104 $a = $self->new_array( [ $this ] );
5105 }
5106 # otherwise this has to be a selector
5107 # TODO: Need to correct this and adjust the object used as a base for the find
5108 # since $self could very well be a dynamically created dom object
5109 else
5110 {
5111 $this = $self->find( $this ) || return;
5112 $a = $self->new_array( [ $this ] );
5113 }
5114 }
5115 elsif( $self->_is_array( $this ) )
5116 {
5117 # Make sure this is a Module::Generic::Array object
5118 $a = $self->new_array( $this );
5119 }
5120 elsif( $self->_is_object( $this ) )
5121 {
5122 return( $self->error( "Object provided '$this' (", overload::StrVal( $this ), ") is not an HTML::Object::DOM::Element object." ) ) if( !$this->isa( 'HTML::Object::DOM::Element' ) );
5123 $a = $self->new_array( [ $this ] );
5124 }
5125 else
5126 {
5127 return( $self->error( "I do not know what to do with \"$this\". I was expecting a selector, html data, an element object or an array." ) );
5128 }
5129  
5130 # If the content to be inserted is a collection, we loop through it, duplicate each element and insert them
5131 if( $self->isa_collection )
5132 {
5133 $a->foreach(sub
5134 {
5135 my $elem = $_;
5136 my $parent = $elem->parent;
5137 return(1) if( !$parent );
5138 $elem->reset(1);
5139 my $pos = $parent->children->pos( $elem );
5140 warn( "Found a parent for tag \"", $elem->tag, "\", but somehow I could not find its position among its children elements.\n" ) if( !defined( $pos ) );
5141 return(1) if( !defined( $pos ) );
5142 $self->children->foreach(sub
5143 {
5144 my $e = shift( @_ );
5145 # Making sure the content element is detached from its original parent
5146 my $clone = $e->detach->clone;
5147 $clone->parent( $elem );
5148 if( $opts->{action} CORE::eq 'before' )
5149 {
5150 $parent->children->splice( $pos, 0, $clone );
5151 }
5152 elsif( $opts->{action} CORE::eq 'after' )
5153 {
5154 $parent->children->splice( $pos + 1, 0, $clone );
5155 }
5156 });
5157 });
5158 }
5159 else
5160 {
5161 # If the target is just one element, we do not duplicate them, but simply move them
5162 if( $a->length == 1 )
5163 {
5164 my $elem = $a->first;
5165 my $parent = $elem->parent;
5166 return(1) if( !$parent );
5167 $elem->reset(1);
5168 my $pos = $parent->children->pos( $elem );
5169 return( $self->error( "Found a parent for tag \"", $elem->tag, "\", but somehow I could not find its position among its children elements." ) ) if( !defined( $pos ) );
5170 $self->detach;
5171 $self->parent( $elem );
5172 if( $opts->{action} CORE::eq 'before' )
5173 {
5174 $parent->children->splice( $pos, 0, $self );
5175 }
5176 elsif( $opts->{action} CORE::eq 'after' )
5177 {
5178 $parent->children->splice( $pos + 1, 0, $self );
5179 }
5180 }
5181 # However, if the target contain multiple element, we clone the content element
5182 else
5183 {
5184 $a->foreach(sub
5185 {
5186 my $elem = $_;
5187 my $parent = $elem->parent;
5188 return(1) if( !$parent );
5189 $elem->reset(1);
5190 my $pos = $parent->children->pos( $elem );
5191 warn( "Found a parent for tag \"", $elem->tag, "\", but somehow I could not find its position among its children elements.\n" ) if( !defined( $pos ) );
5192 return(1) if( !defined( $pos ) );
5193 my $clone = $self->detach->clone;
5194 $clone->parent( $elem );
5195 if( $opts->{action} CORE::eq 'before' )
5196 {
5197 $parent->children->splice( $pos, 0, $clone );
5198 }
5199 elsif( $opts->{action} CORE::eq 'after' )
5200 {
5201 $parent->children->splice( $pos + 1, 0, $clone );
5202 }
5203 });
5204 }
5205 }
5206 return( $self );
5207 }
5208  
5209 sub _is_html { return( $_[1] =~ /^[[:blank:]\h]*<\w+/ ? 1 : 0 ); }
5210  
5211 sub _is_same_node { shift( @_ ); return( shift->eid CORE::eq shift->eid ); }
5212  
5213 sub _xpath_value { shift( @_ ); return( ref( $_[0] ) ? ${$_[0]} : HTML::Selector::XPath::selector_to_xpath( $_[0] ) ); }
5214  
5215 1;
5216 # NOTE: POD
5217 __END__